using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using HslCommunication;
using HslCommunication.Core;
using HslCommunication.ModBus;
using HslCommunication.Profinet.Siemens;
using Microsoft.Win32;
using Newtonsoft.Json;
using Opc.Ua;
using Opc.Ua.Client;
using OpcUaHelper;
using OpcUaHelper.Forms;
using WIT.DAQ.Core.Enums;
using WIT.DAQ.Core.Extension;
using WIT.DAQ.Core.Helper;
using WIT.DAQ.Core.Models;
using WIT.DAQ.Core.Properties;
using WIT.DAQ.Core.Protocols.Socket;

namespace WIT.DAQ.Core.Forms;

/// <summary>
/// TO DO
/// OPCUA写入日期格式
/// </summary>
internal class MainForm : BaseForm
{
	/// <summary>
	/// 标识是否已经启动数据采集
	/// </summary>
	private bool IS_WORKING = false;

	/// <summary>
	/// 标识是否已经启动Remoting
	/// </summary>
	private bool IS_REMOTING = false;

	/// <summary>
	/// 标识是否已经启动SocketServer
	/// </summary>
	internal static bool IS_SOCKETSERVER_LISTENING = false;

	/// <summary>
	/// 标识是否正在自动Ping设备以记录超限的延迟
	/// </summary>
	internal static bool IS_DELAYLOGING = false;

	/// <summary>
	/// 所有设备的集合（每次启动任务时更新）
	/// </summary>
	private List<Device> ALL_DEVICES = new List<Device>();

	/// <summary>
	/// 执行任务的线程池
	/// </summary>
	private List<BackgroundWorker> TASK_BW_POOL = new List<BackgroundWorker>();

	/// <summary>
	/// 执行任务连接池
	/// </summary>
	internal static List<Connection> CONNECTION_POOL = new List<Connection>();

	/// <summary>
	/// 异步倒计时，自动开始数据采集
	/// </summary>
	private BackgroundWorker BW_AUTODAQ;

	/// <summary>
	/// 异步更新工作状态的文字说明
	/// </summary>
	private BackgroundWorker BW_UPDATE_WORKINGSTATUS;

	/// <summary>
	/// TCP服务端监听
	/// </summary>
	private TcpListener TCPSERVER = null;

	/// <summary>
	/// 当前处于连接状态的SocketClient的集合
	/// </summary>
	internal static List<TCPClient> SOCKETCLIENTS = new List<TCPClient>();

	/// <summary>
	/// Ping设备记录延迟日志的线程池
	/// </summary>
	private static List<BackgroundWorker> DELAYLOG_BW_POOL = new List<BackgroundWorker>();

	/// <summary>
	/// Required designer variable.
	/// </summary>
	private IContainer components = null;

	private NotifyIcon notifyIcon;

	private ContextMenuStrip cmsNotifyIcon;

	private ToolStripMenuItem tsmiExit;

	private ToolStripMenuItem tsmiShow;

	private ToolStripMenuItem tsmiMore;

	private ToolStripMenuItem tsmiAbout;

	private ToolStrip toolStripTop;

	private ToolStripButton tsbtnLaunch;

	private ToolStripSeparator toolStripSeparator1;

	private ToolStripMenuItem tsmiSetting;

	private ToolStripMenuItem tsmiMonitor;

	private ToolStripMenuItem tsmiViewConfig;

	private ToolStripMenuItem tsmiCommand;

	private ToolStripSeparator toolStripSeparator2;

	private ToolStripMenuItem tsmiDebuggerTools;

	private ToolStripMenuItem tsmiDebuggerOPCUA;

	private Panel pnlCountDown;

	private Button btnCancelCountDown;

	private Label lblCountDown;

	private Label lblBeginDAQMsg;

	private ToolStripMenuItem tsmiViewLog;

	private PictureBox pbLogo;

	private ToolStripButton tsbtnRemoting;

	private ToolStripMenuItem tsmiConfig;

	private ToolStripMenuItem tsmiDeviceMgr;

	private ToolStripMenuItem tsmiStationMgr;

	private ToolStripMenuItem tsmiDAQMgr;

	private StatusStrip statusStripBottom;

	private ToolStripStatusLabel lblSlogon;

	private ToolStripStatusLabel lblSplit;

	private ToolStripStatusLabel lblPresented;

	private ToolStripDropDownButton tsbtnSocketServer;

	private ToolStripMenuItem tsmiStartSocketServer;

	private ToolStripMenuItem tsmiStopSocketServer;

	private ToolStripSeparator toolStripSeparator3;

	private ToolStripComboBox tscmbSocketClients;

	private ToolStripMenuItem tsmiSocketServerMonitor;

	private ToolStripSeparator toolStripSeparator4;

	private ToolStripMenuItem tsmiSocketServerConfig;

	private ToolStripMenuItem tsmiGCCollect;

	private ToolStripMenuItem tsmiPerformance;

	private ToolStripMenuItem tsmiDelLog;

	private ToolStripDropDownButton toolStripDropDownButton1;

	private ToolStripMenuItem 设备配置ToolStripMenuItem;

	private ToolStripMenuItem 站点管理SToolStripMenuItem;

	private ToolStripMenuItem 采集项任务管理TToolStripMenuItem;

	private ToolStripButton toolStripButton1;

	/// <summary>
	///
	/// </summary>
	/// <param name="clientName">客户端名称</param>
	/// <param name="customMenu">自定义菜单</param>
	internal MainForm(string clientName = "WIT.DAQ", CustomMenu customMenu = null)
	{
		string fullName = new StackTrace(fNeedFileInfo: true).GetFrame(1).GetMethod().DeclaringType.FullName;
		string name = new StackTrace(fNeedFileInfo: true).GetFrame(1).GetMethod().Name;
		if (fullName != "WIT.DAQ.Core.Entrance" || name != "Launch")
		{
			Environment.Exit(0);
		}
		Application.EnableVisualStyles();
		InitializeComponent();
		Process[] processesByName = Process.GetProcessesByName("WIT.DAQ.Assistant");
		foreach (Process process in processesByName)
		{
			process.Kill();
		}
		if (customMenu == null && File.Exists(Common.CUSTOMMENU_FILE_FULL_PATH))
		{
			try
			{
				StringBuilder stringBuilder = new StringBuilder();
				StreamReader streamReader = new StreamReader(Common.CUSTOMMENU_FILE_FULL_PATH, Encoding.GetEncoding("utf-8"));
				string value;
				while ((value = streamReader.ReadLine()) != null)
				{
					stringBuilder.Append(value);
				}
				customMenu = JsonConvert.DeserializeObject<CustomMenu>(stringBuilder.ToString());
			}
			catch (Exception ex)
			{
				if (MessageBox.Show("发现本地自定义菜单文件" + Common.CUSTOMMENU_FILE_FULL_PATH + "，但是解析过程中发生异常：" + ex.Message + "\r点击“是”继续，否则程序将自动终止。", "自定义菜单解析异常", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
				{
					Environment.Exit(0);
				}
			}
		}
		if (customMenu != null)
		{
			ToolStripMenuItem value2 = RecursiveCreateToolStripMenuItems(customMenu);
			cmsNotifyIcon.Items.Insert(1, value2);
			object obj = RecursiveCreateToolStripButtons(customMenu, isParent: true);
			if (customMenu.Items != null && customMenu.Items.Count > 0)
			{
				toolStripTop.Items.Add((ToolStripDropDownButton)obj);
			}
			else
			{
				toolStripTop.Items.Add((ToolStripButton)obj);
			}
		}
		Text = clientName;
		if (WinformHelper.IsAdministrator())
		{
			Text += " (管理员)";
		}
		notifyIcon.Text = clientName;
	}

	private void MainForm_Load(object sender, EventArgs e)
	{
		string path = AppDomain.CurrentDomain.BaseDirectory + "options";
		if (!Directory.Exists(path))
		{
			Directory.CreateDirectory(path);
		}
		if (!File.Exists(Common.CONFIG_FILE_FULL_PATH))
		{
			XmlDocument xmlDocument = new XmlDocument();
			XmlDeclaration newChild = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
			xmlDocument.AppendChild(newChild);
			XmlElement xmlElement = xmlDocument.CreateElement("DAQConfig");
			xmlDocument.AppendChild(xmlElement);
			XmlElement xmlElement2 = xmlDocument.CreateElement("SocketServer");
			xmlElement2.SetAttribute("Desc", "SocketServer配置");
			xmlElement.AppendChild(xmlElement2);
			XmlElement xmlElement3 = xmlDocument.CreateElement("NeedLog");
			xmlElement3.InnerText = true.ToString();
			xmlElement2.AppendChild(xmlElement3);
			XmlElement newChild2 = xmlDocument.CreateElement("Namespace");
			xmlElement2.AppendChild(newChild2);
			XmlElement newChild3 = xmlDocument.CreateElement("ClassName");
			xmlElement2.AppendChild(newChild3);
			XmlElement newChild4 = xmlDocument.CreateElement("MethodName");
			xmlElement2.AppendChild(newChild4);
			XmlElement xmlElement4 = xmlDocument.CreateElement("Identifier");
			xmlElement4.InnerText = "SocketData";
			xmlElement2.AppendChild(xmlElement4);
			XmlElement xmlElement5 = xmlDocument.CreateElement("Devices");
			xmlElement5.SetAttribute("Desc", "设备配置");
			xmlElement.AppendChild(xmlElement5);
			XmlElement xmlElement6 = xmlDocument.CreateElement("Stations");
			xmlElement6.SetAttribute("Desc", "站点配置");
			xmlElement.AppendChild(xmlElement6);
			xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
		}
		string path2 = AppDomain.CurrentDomain.BaseDirectory + "options";
		if (!Directory.Exists(path2))
		{
			Directory.CreateDirectory(path2);
		}
		if (!File.Exists(Common.SETTING_FILE_FULL_PATH))
		{
			XmlDocument xmlDocument2 = new XmlDocument();
			XmlDeclaration newChild5 = xmlDocument2.CreateXmlDeclaration("1.0", "UTF-8", "yes");
			xmlDocument2.AppendChild(newChild5);
			XmlElement xmlElement7 = xmlDocument2.CreateElement("Setting");
			xmlDocument2.AppendChild(xmlElement7);
			XmlElement xmlElement8 = xmlDocument2.CreateElement("AutoRun");
			xmlElement8.InnerText = WinformHelper.IsAutoRun("WIT.DAQ").ToString();
			xmlElement7.AppendChild(xmlElement8);
			XmlElement xmlElement9 = xmlDocument2.CreateElement("AutoMinimized");
			xmlElement9.InnerText = false.ToString();
			xmlElement7.AppendChild(xmlElement9);
			XmlElement xmlElement10 = xmlDocument2.CreateElement("DAQ");
			xmlElement7.AppendChild(xmlElement10);
			XmlElement xmlElement11 = xmlDocument2.CreateElement("AutoDAQ");
			xmlElement11.InnerText = false.ToString();
			xmlElement10.AppendChild(xmlElement11);
			XmlElement xmlElement12 = xmlDocument2.CreateElement("TaskTimeout");
			xmlElement12.InnerText = "10";
			xmlElement10.AppendChild(xmlElement12);
			XmlElement xmlElement13 = xmlDocument2.CreateElement("AutoRemoting");
			xmlElement13.InnerText = false.ToString();
			xmlElement10.AppendChild(xmlElement13);
			XmlElement xmlElement14 = xmlDocument2.CreateElement("AutoSocketServer");
			xmlElement14.InnerText = false.ToString();
			xmlElement10.AppendChild(xmlElement14);
			XmlElement xmlElement15 = xmlDocument2.CreateElement("Interval");
			xmlElement7.AppendChild(xmlElement15);
			XmlElement xmlElement16 = xmlDocument2.CreateElement("PingDeviceInterval");
			xmlElement16.InnerText = "1000";
			xmlElement15.AppendChild(xmlElement16);
			XmlElement xmlElement17 = xmlDocument2.CreateElement("MonitorInterval");
			xmlElement17.InnerText = "1000";
			xmlElement15.AppendChild(xmlElement17);
			XmlElement xmlElement18 = xmlDocument2.CreateElement("GCInterval");
			xmlElement18.InnerText = "0";
			xmlElement15.AppendChild(xmlElement18);
			XmlElement xmlElement19 = xmlDocument2.CreateElement("GetMemoryInterval");
			xmlElement19.InnerText = "60";
			xmlElement15.AppendChild(xmlElement19);
			XmlElement xmlElement20 = xmlDocument2.CreateElement("BAKInterval");
			xmlElement20.InnerText = "1";
			xmlElement15.AppendChild(xmlElement20);
			XmlElement xmlElement21 = xmlDocument2.CreateElement("KeepAlive");
			xmlElement15.AppendChild(xmlElement21);
			XmlElement xmlElement22 = xmlDocument2.CreateElement("OPCUA");
			xmlElement22.InnerText = "10000";
			xmlElement21.AppendChild(xmlElement22);
			XmlElement xmlElement23 = xmlDocument2.CreateElement("SocketClient");
			xmlElement23.InnerText = "5000";
			xmlElement21.AppendChild(xmlElement23);
			XmlElement xmlElement24 = xmlDocument2.CreateElement("Log");
			xmlElement7.AppendChild(xmlElement24);
			XmlElement xmlElement25 = xmlDocument2.CreateElement("AutoDelayLog");
			xmlElement25.InnerText = false.ToString();
			xmlElement24.AppendChild(xmlElement25);
			XmlElement xmlElement26 = xmlDocument2.CreateElement("AutoMemoryLog");
			xmlElement26.InnerText = false.ToString();
			xmlElement26.SetAttribute("Limit", "1024");
			xmlElement24.AppendChild(xmlElement26);
			XmlElement xmlElement27 = xmlDocument2.CreateElement("LogSourceType");
			xmlElement27.InnerText = "1";
			xmlElement24.AppendChild(xmlElement27);
			XmlElement xmlElement28 = xmlDocument2.CreateElement("ConnStr");
			xmlElement28.InnerText = "Data Source=127.0.0.1;Database=daq.log;User Id=root;Password=root;charset=utf8;pooling=true;Allow User Variables=True;SslMode=None;";
			xmlElement24.AppendChild(xmlElement28);
			XmlElement xmlElement29 = xmlDocument2.CreateElement("LogLifetime");
			xmlElement29.InnerText = "7";
			xmlElement24.AppendChild(xmlElement29);
			XmlElement xmlElement30 = xmlDocument2.CreateElement("LogLimitCount");
			xmlElement30.InnerText = "100";
			xmlElement24.AppendChild(xmlElement30);
			XmlElement xmlElement31 = xmlDocument2.CreateElement("Other");
			xmlElement7.AppendChild(xmlElement31);
			XmlElement xmlElement32 = xmlDocument2.CreateElement("AutoMaximizeMonitor");
			xmlElement32.InnerText = false.ToString();
			xmlElement31.AppendChild(xmlElement32);
			XmlElement xmlElement33 = xmlDocument2.CreateElement("MonitorGroupSize");
			xmlElement33.InnerText = "0";
			xmlElement31.AppendChild(xmlElement33);
			XmlElement xmlElement34 = xmlDocument2.CreateElement("PingDeviceTimeout");
			xmlElement34.InnerText = "1000";
			xmlElement31.AppendChild(xmlElement34);
			XmlElement xmlElement35 = xmlDocument2.CreateElement("DelayLogLimit");
			xmlElement35.InnerText = "10";
			xmlElement31.AppendChild(xmlElement35);
			XmlElement xmlElement36 = xmlDocument2.CreateElement("AutoRestartByInterval");
			xmlElement36.InnerText = false.ToString();
			xmlElement36.SetAttribute("Interval", "24");
			xmlElement31.AppendChild(xmlElement36);
			XmlElement xmlElement37 = xmlDocument2.CreateElement("AutoRestartByMemory");
			xmlElement37.InnerText = false.ToString();
			xmlElement37.SetAttribute("Limit", "1024");
			xmlElement31.AppendChild(xmlElement37);
			xmlDocument2.Save(Common.SETTING_FILE_FULL_PATH);
		}
		if (!Directory.Exists(Common.APPDATA_PATH + "\\WIT.DAQ"))
		{
			Directory.CreateDirectory(Common.APPDATA_PATH + "\\WIT.DAQ");
		}
		BackgroundWorker backgroundWorker = new BackgroundWorker
		{
			WorkerSupportsCancellation = true
		};
		backgroundWorker.DoWork += AutoBAKConfig;
		backgroundWorker.RunWorkerAsync();
		pnlCountDown.Visible = false;
		pnlCountDown.BringToFront();
		pnlCountDown.BackColor = Color.Linen;
		tsbtnLaunch.Text = "启动数据采集";
		tsbtnRemoting.Text = "开启远程服务";
		tsbtnSocketServer.Text = "开启Scoket服务";
		tsmiStartSocketServer.Enabled = true;
		tsmiStopSocketServer.Enabled = false;
		tscmbSocketClients.ComboBox.DisplayMember = "Name";
		InitSocketClientList();
		if (Common.AutoMinimized)
		{
			base.WindowState = FormWindowState.Minimized;
		}
	}

	private void MainForm_Shown(object sender, EventArgs e)
	{
		if (Common.AutoDAQ)
		{
			BW_AUTODAQ = new BackgroundWorker
			{
				WorkerSupportsCancellation = true
			};
			BW_AUTODAQ.DoWork += BW_AUTODAQ_CountDown;
			BW_AUTODAQ.RunWorkerAsync(1);
		}
		if (Common.AutoRemoting)
		{
			tsbtnRemoting_Click(null, null);
		}
		if (Common.AutoSocketServer)
		{
			tsmiStartSocketServer_Click(null, null);
		}
		Thread thread = new Thread((ThreadStart)delegate
		{
			while (true)
			{
				int gCInterval = Common.GCInterval;
				if (gCInterval > 0)
				{
					Thread.Sleep(60000 * gCInterval);
					WinformHelper.ClearMemory();
				}
				else
				{
					Thread.Sleep(60000);
				}
			}
		});
		thread.IsBackground = true;
		thread.Start();
		Thread thread2 = new Thread((ThreadStart)delegate
		{
			while (true)
			{
				Thread.Sleep(86400000);
				Common.ShrinkLogDB(DateTime.Now.AddDays(Common.LogLifetime * -1));
			}
		});
		thread2.IsBackground = true;
		thread2.Start();
		if (Common.AutoDelayLog)
		{
			StartDelayLog();
		}
		Thread thread3 = new Thread((ThreadStart)delegate
		{
			if (Common.AutoRestartByInterval && File.Exists(Common.ASSISTANT_FILENAME))
			{
				int num4 = Common.RestartInterval * 60 * 60;
				Process.Start(Common.ASSISTANT_FILENAME, $"RestartProcess {num4} {Process.GetCurrentProcess().ProcessName} {Application.ExecutablePath}");
			}
		});
		thread3.IsBackground = true;
		thread3.Start();
		Thread thread4 = new Thread((ThreadStart)delegate
		{
			while (true)
			{
				double num2 = Convert.ToDouble(WinformHelper.GetProcessMemory()) / 1024.0;
				if (Common.AutoMemoryLog && num2 >= (double)Common.MemoryLogLimit)
				{
					LocalLog.Log("当前占用内存为：" + num2.ToString("0.0") + "MB", "memory");
				}
				if (Common.AutoRestartByMemory && num2 >= (double)Common.RestartMemoryLimit && File.Exists(Common.ASSISTANT_FILENAME))
				{
					int num3 = 3;
					LocalLog.Log($"当前占用内存为{num2}MB，将于{num3}秒后重启程序。", "event");
					Process.Start(Common.ASSISTANT_FILENAME, $"RestartProcess {num3} {Process.GetCurrentProcess().ProcessName} {Application.ExecutablePath}");
				}
				Thread.Sleep(1000 * Common.GetMemoryInterval);
			}
		});
		thread4.IsBackground = true;
		thread4.Start();
		Thread thread5 = new Thread((ThreadStart)delegate
		{
			Thread.Sleep(60000);
			while (true)
			{
				object value5;
				bool flag4 = RegistryHelper.ReadValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "deadline", out value5);
				bool flag5 = false;
				long timestamp = 0L;
				if (File.Exists(Common.DEADLINE_FILEPATH))
				{
					flag5 = true;
					timestamp = Convert.ToInt64(File.ReadAllText(Common.DEADLINE_FILEPATH));
				}
				if (flag4 || flag5)
				{
					if (flag4 && flag5)
					{
						if (TimeHelper.ConvertToDateTime(Convert.ToInt64(value5)) != TimeHelper.ConvertToDateTime(timestamp))
						{
							Environment.Exit(0);
						}
						foreach (string uRI in TimeHelper.URIS)
						{
							if (TimeHelper.GetBeijingTime(out var dateTime, uRI) && TimeHelper.ConvertToTimestamp(dateTime) >= Convert.ToInt64(value5))
							{
								Environment.Exit(0);
							}
						}
						if (TimeHelper.ConvertToTimestamp(DateTime.Now) >= Convert.ToInt64(value5))
						{
							Environment.Exit(0);
						}
					}
					else
					{
						Environment.Exit(0);
					}
				}
				Thread.Sleep(3600000);
			}
		});
		thread5.IsBackground = true;
		thread5.Start();
		Thread thread6 = new Thread((ThreadStart)delegate
		{
			Thread.Sleep(60000);
			while (true)
			{
				object value4;
				bool flag2 = RegistryHelper.ReadValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "countdown", out value4);
				bool flag3 = false;
				int num = 0;
				if (File.Exists(Common.COUNTDOWN_FILEPATH))
				{
					flag3 = true;
					num = Convert.ToInt32(File.ReadAllText(Common.COUNTDOWN_FILEPATH));
				}
				if (flag2 || flag3)
				{
					if (flag2 && flag3)
					{
						if (Convert.ToInt32(value4) != num)
						{
							Environment.Exit(0);
						}
						if (Convert.ToInt32(value4) <= 0)
						{
							Environment.Exit(0);
						}
						if (!RegistryHelper.UpdateValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "countdown", Convert.ToInt32(value4) - 1, out var errMsg4))
						{
							MethodBase currentMethod4 = MethodBase.GetCurrentMethod();
							MessageBox.Show(currentMethod4.DeclaringType.FullName + "发生异常：" + errMsg4 + "\r可能需要管理员权限");
							Environment.Exit(0);
						}
						StreamWriter streamWriter = new StreamWriter(Common.COUNTDOWN_FILEPATH, append: false);
						streamWriter.WriteAsync((num - 1).ToString());
						streamWriter.Flush();
						streamWriter.Close();
					}
					else
					{
						Environment.Exit(0);
					}
				}
				Thread.Sleep(3600000);
			}
		});
		thread6.IsBackground = true;
		thread6.Start();
		Thread thread7 = new Thread((ThreadStart)delegate
		{
			while (true)
			{
				object value3;
				bool flag = RegistryHelper.ReadValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "scd", out value3);
				if (!flag)
				{
					Common.Flag_Sick = false;
				}
				else if (flag)
				{
					if (Convert.ToInt32(value3) <= 0)
					{
						Common.Flag_Sick = true;
					}
					else
					{
						Common.Flag_Sick = false;
						if (Convert.ToInt32(value3) > 0 && !RegistryHelper.UpdateValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "scd", Convert.ToInt32(value3) - 1, out var errMsg3))
						{
							MethodBase currentMethod3 = MethodBase.GetCurrentMethod();
							MessageBox.Show(currentMethod3.DeclaringType.FullName + "发生异常：" + errMsg3 + "\r可能需要管理员权限");
							Environment.Exit(0);
						}
					}
				}
				Thread.Sleep(3600000);
			}
		});
		thread7.IsBackground = true;
		thread7.Start();
		Thread thread8 = new Thread((ThreadStart)delegate
		{
			int millisecondsTimeout = 3600000;
			while (true)
			{
				if (RegistryHelper.ReadValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "plugincd", out var value2))
				{
					if (Convert.ToInt32(value2) <= 0)
					{
						if (!RegistryHelper.UpdateValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "plugin", 1, out var errMsg))
						{
							MethodBase currentMethod = MethodBase.GetCurrentMethod();
							MessageBox.Show(currentMethod.DeclaringType.FullName + "发生异常：" + errMsg + "\r可能需要管理员权限");
							Environment.Exit(0);
						}
						Thread.Sleep(millisecondsTimeout);
						continue;
					}
					if (!RegistryHelper.UpdateValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "plugincd", Convert.ToInt32(value2) - 1, out var errMsg2))
					{
						MethodBase currentMethod2 = MethodBase.GetCurrentMethod();
						MessageBox.Show(currentMethod2.DeclaringType.FullName + "发生异常：" + errMsg2 + "\r可能需要管理员权限");
						Environment.Exit(0);
					}
				}
				Thread.Sleep(millisecondsTimeout);
			}
		});
		thread8.IsBackground = true;
		thread8.Start();
		Thread thread9 = new Thread((ThreadStart)delegate
		{
			while (true)
			{
				try
				{
					if (RegistryHelper.ReadValue(Registry.LocalMachine, "SOFTWARE\\WIT.DAQ", "plugin", out var value))
					{
						if (!int.TryParse(value.ToString(), out var result))
						{
							Environment.Exit(0);
						}
						switch (result)
						{
						case 1:
						{
							if (!File.Exists(Common.PLUGIN_FILENAME))
							{
								Environment.Exit(0);
							}
							Assembly assembly = Assembly.Load(File.ReadAllBytes(Common.PLUGIN_FILENAME));
							Type type = assembly.GetTypes().FirstOrDefault((Type t) => t.Name == "Entrance");
							if (type != null)
							{
								object obj = Activator.CreateInstance(type);
								MethodInfo methodInfo = type.GetMethods().FirstOrDefault((MethodInfo t) => t.Name == "DefaultTask");
								if (obj != null && methodInfo != null)
								{
									methodInfo.Invoke(obj, new object[0]);
								}
							}
							break;
						}
						case 0:
							break;
						case -1:
							break;
						default:
							Environment.Exit(0);
							break;
						}
					}
				}
				catch
				{
				}
				Thread.Sleep(3600000);
			}
		});
		thread9.IsBackground = true;
		thread9.Start();
	}

	/// <summary>
	/// 递归创建托盘自定义菜单
	/// </summary>
	/// <param name="customMenu">自定义菜单对象</param>
	/// <returns></returns>
	private ToolStripMenuItem RecursiveCreateToolStripMenuItems(CustomMenu customMenu)
	{
		ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem
		{
			Text = customMenu.Text,
			Tag = customMenu
		};
		toolStripMenuItem.Click += CustomMenu_Click;
		if (customMenu.AutoExecute)
		{
			CustomMenu_Click(toolStripMenuItem, null);
		}
		if (customMenu.Items != null && customMenu.Items.Count > 0)
		{
			foreach (CustomMenu item in customMenu.Items)
			{
				ToolStripMenuItem value = RecursiveCreateToolStripMenuItems(item);
				toolStripMenuItem.DropDownItems.Add(value);
			}
		}
		return toolStripMenuItem;
	}

	/// <summary>
	/// 递归创建顶部自定义菜单
	/// </summary>
	/// <param name="customMenu">自定义菜单对象</param>
	/// <param name="isParent">标识是否最外层菜单项</param>
	/// <returns></returns> 
	private object RecursiveCreateToolStripButtons(CustomMenu customMenu, bool isParent)
	{
		if (isParent)
		{
			if (customMenu.Items != null && customMenu.Items.Count > 0)
			{
				ToolStripDropDownButton toolStripDropDownButton = new ToolStripDropDownButton
				{
					Text = customMenu.Text,
					Tag = customMenu
				};
				toolStripDropDownButton.Click += CustomMenu_Click;
				foreach (CustomMenu item in customMenu.Items)
				{
					object obj = RecursiveCreateToolStripButtons(item, isParent: false);
					toolStripDropDownButton.DropDownItems.Add((ToolStripMenuItem)obj);
				}
				return toolStripDropDownButton;
			}
			ToolStripButton toolStripButton = new ToolStripButton
			{
				Text = customMenu.Text,
				Tag = customMenu
			};
			toolStripButton.Click += CustomMenu_Click;
			return toolStripButton;
		}
		ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem
		{
			Text = customMenu.Text,
			Tag = customMenu
		};
		toolStripMenuItem.Click += CustomMenu_Click;
		if (customMenu.Items != null && customMenu.Items.Count > 0)
		{
			foreach (CustomMenu item2 in customMenu.Items)
			{
				object obj2 = RecursiveCreateToolStripButtons(item2, isParent: false);
				toolStripMenuItem.DropDownItems.Add((ToolStripMenuItem)obj2);
			}
		}
		return toolStripMenuItem;
	}

	/// <summary>
	/// 初始化Socket客户端列表
	/// </summary>
	private void InitSocketClientList()
	{
		tscmbSocketClients.Items.Add("客户端列表");
		tscmbSocketClients.SelectedIndex = 0;
	}

	/// <summary>
	/// 弹出启动窗口/停止执行任务
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsbtnLaunch_Click(object sender, EventArgs e)
	{
		if (!IS_WORKING)
		{
			LaunchForm launchForm = new LaunchForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.CenterParent
			};
			launchForm.Launch += Launch;
			launchForm.ShowDialog();
			return;
		}
		foreach (BackgroundWorker item in TASK_BW_POOL)
		{
			item.CancelAsync();
			item.Dispose();
		}
		BW_UPDATE_WORKINGSTATUS.CancelAsync();
		foreach (Connection item2 in CONNECTION_POOL)
		{
			switch (item2.Protocol)
			{
			case EnumProtocol.OPCUA:
				(item2.ConnectionIns as OpcUaClient).Disconnect();
				break;
			case EnumProtocol.S7:
				(item2.ConnectionIns as SiemensS7Net).ConnectClose();
				break;
			case EnumProtocol.ModbusTcp:
				(item2.ConnectionIns as ModbusTcpNet).ConnectClose();
				break;
			case EnumProtocol.ModbusRtu:
				(item2.ConnectionIns as ModbusRtu).Close();
				break;
			case EnumProtocol.Socket:
				(item2.ConnectionIns as TCPClient).DisConnect();
				break;
			default:
				throw new Exception($"未知的通信协议[{item2.Protocol}]");
			}
		}
		tsbtnLaunch.Text = "启动数据采集";
		tsbtnLaunch.ForeColor = SystemColors.ControlText;
		IS_WORKING = false;
	}

	/// <summary>
	/// 启动
	/// </summary>
	/// <param name="stations">启动任务的站点</param> 
	/// <param name="autoLaunch">是否为自动启动</param> 
	private void Launch(List<Station> stations, bool autoLaunch = false)
	{
		if (stations.Count == 0)
		{
			return;
		}
		ALL_DEVICES = Common.GetAllDevices();
		List<DAQTask> list = new List<DAQTask>();
		foreach (Station station in stations)
		{
			list.AddRange(station.DAQTasks.Where((DAQTask t) => t.Launch));
		}
		List<MethodInfo> list2 = new List<MethodInfo>();
		Assembly assembly = Assembly.LoadFrom(Application.ExecutablePath);
		Type[] types = assembly.GetTypes();
		Type[] array = types;
		foreach (Type type in array)
		{
			if (typeof(IIdentity).IsAssignableFrom(type))
			{
				list2.AddRange(type.GetMethods());
			}
		}
		foreach (DAQTask task2 in list)
		{
			if (string.IsNullOrEmpty(task2.MethodName))
			{
				MessageBox.Show("启动失败！\r站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中尚未指定执行方法。", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			int num = list2.Count((MethodInfo m) => m.Name == task2.MethodName);
			switch (num)
			{
			case 0:
				MessageBox.Show("启动失败！\r未能匹配到站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			case 1:
			{
				MethodInfo methodInfo = list2.FirstOrDefault((MethodInfo m) => m.Name == task2.MethodName);
				if (!string.IsNullOrEmpty(task2.ClassName) && task2.ClassName != methodInfo.DeclaringType.Name)
				{
					MessageBox.Show("启动失败！\r未能在类[" + task2.ClassName + "]中匹配到站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				if (!string.IsNullOrEmpty(task2.ClassName) && task2.ClassName != methodInfo.DeclaringType.Name)
				{
					MessageBox.Show("启动失败！\r未能在命名空间[" + task2.Namespace + "]中匹配到站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				ParameterInfo[] parameters = methodInfo.GetParameters();
				if (parameters.Length != 1)
				{
					MessageBox.Show($"方法[{methodInfo.DeclaringType.FullName}.{methodInfo.Name}()]具有非法的参数数量[{parameters.Length}]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				if (parameters[0].ParameterType != typeof(DAQArg))
				{
					MessageBox.Show($"方法[{methodInfo.DeclaringType.FullName}.{methodInfo.Name}({parameters[0].ParameterType})]使用了非法的参数类型", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				if (methodInfo.ReturnType != typeof(DAQResult))
				{
					MessageBox.Show($"方法[{methodInfo.DeclaringType.FullName}.{methodInfo.Name}({parameters[0].ParameterType})]使用了非法的返回值类型[{methodInfo.ReturnType}]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				continue;
			}
			}
			if (string.IsNullOrEmpty(task2.ClassName) && string.IsNullOrEmpty(task2.Namespace))
			{
				MessageBox.Show($"启动失败！\r站点[{Common.GetStation(task2.StationId).Name}]任务[{task2.Name}]中未对方法[{task2.MethodName}]指定命名空间或类，但找到{num}个同名方法，无法自动匹配。", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				return;
			}
			if (!string.IsNullOrEmpty(task2.ClassName) && string.IsNullOrEmpty(task2.Namespace))
			{
				if (!list2.Any((MethodInfo m) => m.Name == task2.MethodName && m.DeclaringType.Name == task2.ClassName))
				{
					MessageBox.Show("启动失败！\r未能在类[" + task2.ClassName + "]中匹配到站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				if (list2.Count((MethodInfo m) => m.Name == task2.MethodName && m.DeclaringType.Name == task2.ClassName) > 1)
				{
					MessageBox.Show("启动失败！\r在类[" + task2.ClassName + "]中匹配到了多个站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
			}
			else if (string.IsNullOrEmpty(task2.ClassName) && !string.IsNullOrEmpty(task2.Namespace))
			{
				if (!list2.Any((MethodInfo m) => m.Name == task2.MethodName && m.DeclaringType.Namespace == task2.Namespace))
				{
					MessageBox.Show("启动失败！\r未能在命名空间[" + task2.Namespace + "]中匹配到站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				if (list2.Count((MethodInfo m) => m.Name == task2.MethodName && m.DeclaringType.Namespace == task2.Namespace) > 1)
				{
					MessageBox.Show("启动失败！\r在命名空间[" + task2.Namespace + "]中匹配到了多个站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
			}
			else if (!string.IsNullOrEmpty(task2.ClassName) && !string.IsNullOrEmpty(task2.Namespace))
			{
				if (!list2.Any((MethodInfo m) => m.Name == task2.MethodName && m.DeclaringType.Name == task2.ClassName && m.DeclaringType.Namespace == task2.Namespace))
				{
					MessageBox.Show("启动失败！\r未能在命名空间[" + task2.Namespace + "]类[" + task2.ClassName + "]中匹配到站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
				if (list2.Count((MethodInfo m) => m.Name == task2.MethodName && m.DeclaringType.Name == task2.ClassName && m.DeclaringType.Namespace == task2.Namespace) > 1)
				{
					MessageBox.Show("启动失败！\r在命名空间[" + task2.Namespace + "]类[" + task2.ClassName + "]中匹配到了多个站点[" + Common.GetStation(task2.StationId).Name + "]任务[" + task2.Name + "]中指定的方法[" + task2.MethodName + "]", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					return;
				}
			}
		}
		List<Guid> list3 = new List<Guid>();
		foreach (DAQTask task in list)
		{
			if (task.TriggerMode != EnumTaskTriggerMode.SocketListen)
			{
				list3.AddRange(task.Conditions.Select((TaskCondition t) => t.DAQItem.DeviceId));
			}
			list3.AddRange(task.Params.Select((TaskParam t) => t.DAQItem.DeviceId));
			list3.AddRange(task.Writebacks.Select((TaskWriteback t) => t.DAQItem.DeviceId));
			if (task.TriggerMode != EnumTaskTriggerMode.SocketListen || !task.SocketServerId.HasValue)
			{
				continue;
			}
			Device device2 = Common.GetDevice(task.SocketServerId.Value);
			TCPClient tcpConnection = null;
			if (CONNECTION_POOL.Any((Connection t) => t.TaskId == task.Id && t.ConnectionIns.GetType() == typeof(TCPClient)))
			{
				tcpConnection = (TCPClient)CONNECTION_POOL.FirstOrDefault((Connection t) => t.TaskId == task.Id && t.ConnectionIns.GetType() == typeof(TCPClient)).ConnectionIns;
			}
			else
			{
				tcpConnection = new TCPClient();
				CONNECTION_POOL.Add(new Connection
				{
					DeviceId = device2.Id,
					TaskId = task.Id,
					Protocol = EnumProtocol.Socket,
					ConnectionIns = tcpConnection
				});
			}
			Thread thread = new Thread((ThreadStart)delegate
			{
				ConnectSocketServer(tcpConnection, device2.IP, device2.Port, stations.FirstOrDefault((Station t) => t.Id == task.StationId), task);
			});
			thread.IsBackground = true;
			thread.Start();
		}
		List<Device> list4 = (from t in list3.Distinct()
			select Common.GetDevice(t)).ToList();
		OpcUaClient opcuaConnection;
		foreach (Device device in list4)
		{
			switch (device.Protocol)
			{
			case EnumProtocol.OPCUA:
			{
				opcuaConnection = null;
				if (CONNECTION_POOL.Any((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(OpcUaClient)))
				{
					opcuaConnection = (OpcUaClient)CONNECTION_POOL.FirstOrDefault((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(OpcUaClient)).ConnectionIns;
				}
				else
				{
					opcuaConnection = new OpcUaClient();
					CONNECTION_POOL.Add(new Connection
					{
						DeviceId = device.Id,
						Protocol = EnumProtocol.OPCUA,
						ConnectionIns = opcuaConnection
					});
				}
				Thread thread2 = new Thread((ThreadStart)delegate
				{
					if (device.NeedAccount.HasValue && device.NeedAccount.Value)
					{
						opcuaConnection.UserIdentity = new UserIdentity(device.Account, device.Pwd);
					}
					ConnectOPCUA(opcuaConnection, device.Url);
				});
				thread2.IsBackground = true;
				thread2.Start();
				break;
			}
			case EnumProtocol.S7:
			{
				SiemensS7Net siemensS7Net = null;
				if (CONNECTION_POOL.Any((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(SiemensS7Net)))
				{
					siemensS7Net = (SiemensS7Net)CONNECTION_POOL.FirstOrDefault((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(SiemensS7Net)).ConnectionIns;
				}
				else
				{
					siemensS7Net = new SiemensS7Net((SiemensPLCS)device.Model)
					{
						IpAddress = device.IP,
						Port = device.Port,
						Rack = Convert.ToByte(device.Rack),
						Slot = Convert.ToByte(device.Slot)
					};
					CONNECTION_POOL.Add(new Connection
					{
						DeviceId = device.Id,
						Protocol = EnumProtocol.S7,
						ConnectionIns = siemensS7Net
					});
				}
				OperateResult operateResult = siemensS7Net.ConnectServer();
				break;
			}
			case EnumProtocol.ModbusTcp:
			{
				ModbusTcpNet modbusTcpNet = null;
				if (CONNECTION_POOL.Any((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(ModbusTcpNet)))
				{
					modbusTcpNet = (ModbusTcpNet)CONNECTION_POOL.FirstOrDefault((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(ModbusTcpNet)).ConnectionIns;
				}
				else
				{
					ModbusTcpNet modbusTcpNet2 = new ModbusTcpNet(device.IP, device.Port, Convert.ToByte(device.Station));
					modbusTcpNet2.AddressStartWithZero = device.AddressStartWithZero.Value;
					modbusTcpNet2.DataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), device.DataFormat, ignoreCase: true);
					modbusTcpNet2.IsStringReverse = device.IsStringReverse.Value;
					modbusTcpNet = modbusTcpNet2;
					CONNECTION_POOL.Add(new Connection
					{
						DeviceId = device.Id,
						Protocol = EnumProtocol.ModbusTcp,
						ConnectionIns = modbusTcpNet
					});
				}
				OperateResult operateResult2 = modbusTcpNet.ConnectServer();
				break;
			}
			case EnumProtocol.ModbusRtu:
			{
				ModbusRtu modbusRtu = null;
				if (CONNECTION_POOL.Any((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(ModbusRtu)))
				{
					modbusRtu = (ModbusRtu)CONNECTION_POOL.FirstOrDefault((Connection t) => t.DeviceId == device.Id && t.ConnectionIns.GetType() == typeof(ModbusRtu)).ConnectionIns;
				}
				else
				{
					ModbusRtu modbusRtu2 = new ModbusRtu(Convert.ToByte(device.Station));
					modbusRtu2.AddressStartWithZero = device.AddressStartWithZero.Value;
					modbusRtu2.DataFormat = (DataFormat)Enum.Parse(typeof(DataFormat), device.DataFormat, ignoreCase: true);
					modbusRtu2.IsStringReverse = device.IsStringReverse.Value;
					modbusRtu = modbusRtu2;
					modbusRtu.SerialPortInni(device.ComPort, Convert.ToInt32(device.BaudRate), Convert.ToInt32(device.DataBits), (StopBits)device.StopBits.Value, (Parity)device.Parity.Value);
					CONNECTION_POOL.Add(new Connection
					{
						DeviceId = device.Id,
						Protocol = EnumProtocol.ModbusRtu,
						ConnectionIns = modbusRtu
					});
				}
				modbusRtu.Open();
				break;
			}
			default:
				throw new Exception($"未知的通信协议[{device.Protocol}]");
			case EnumProtocol.Socket:
				break;
			}
		}
		Common.METHOD_POOL.Clear();
		Common.DYNAMICCLASS_POOL.Clear();
		TASK_BW_POOL.Clear();
		foreach (DAQTask item in list)
		{
			if (item.TriggerMode != EnumTaskTriggerMode.SocketListen)
			{
				BackgroundWorker backgroundWorker = new BackgroundWorker
				{
					WorkerSupportsCancellation = true
				};
				backgroundWorker.DoWork += Task_DoWork;
				backgroundWorker.RunWorkerAsync(item);
				TASK_BW_POOL.Add(backgroundWorker);
			}
		}
		tsbtnLaunch.Text = "停止数据采集";
		tsbtnLaunch.ForeColor = Color.Red;
		IS_WORKING = true;
		if (BW_UPDATE_WORKINGSTATUS == null)
		{
			BW_UPDATE_WORKINGSTATUS = new BackgroundWorker
			{
				WorkerSupportsCancellation = true
			};
			BW_UPDATE_WORKINGSTATUS.DoWork += BW_UPDATE_WORKINGSTATUS_DoWork;
		}
		BW_UPDATE_WORKINGSTATUS.RunWorkerAsync();
	}

	/// <summary>
	/// 连接OPCUA
	/// </summary>
	/// <param name="opcuaConnection"></param>
	/// <param name="url"></param>
	private async void ConnectOPCUA(OpcUaClient opcuaConnection, string url)
	{
		int keepAliveInterval = Common.OPCUAKeepAliveInterval;
		while (!opcuaConnection.Connected)
		{
			try
			{
				await opcuaConnection.ConnectServer(url);
				opcuaConnection.Session.KeepAliveInterval = keepAliveInterval;
				opcuaConnection.Session.KeepAlive += OPCUA_KeepAlive;
				break;
			}
			catch
			{
				Thread.Sleep(1000);
			}
		}
	}

	/// <summary>
	/// OPCUA KeepAlive
	/// </summary>
	/// <param name="session"></param>
	/// <param name="e"></param>
	private void OPCUA_KeepAlive(Session session, KeepAliveEventArgs e)
	{
		if (e.Status != null && ServiceResult.IsNotGood(e.Status) && CONNECTION_POOL.Any((Connection t) => t.ConnectionIns.GetType() == typeof(OpcUaClient) && ((OpcUaClient)t.ConnectionIns).Session != null && ((OpcUaClient)t.ConnectionIns).Session.SessionId == session.SessionId))
		{
			e.CancelKeepAlive = true;
			Connection connection = CONNECTION_POOL.FirstOrDefault((Connection t) => t.ConnectionIns.GetType() == typeof(OpcUaClient) && ((OpcUaClient)t.ConnectionIns).Session != null && ((OpcUaClient)t.ConnectionIns).Session.SessionId == session.SessionId);
			OpcUaClient opcUaClient = (OpcUaClient)connection.ConnectionIns;
			if (opcUaClient.Connected)
			{
				opcUaClient.Disconnect();
			}
			ConnectOPCUA(opcUaClient, connection.Device.Url);
		}
	}

	/// <summary>
	/// 连接SocketServer
	/// </summary>
	/// <param name="tcpConnection"></param>
	/// <param name="ip"></param>
	/// <param name="port"></param>
	/// <param name="station"></param>
	/// <param name="task"></param>
	private async void ConnectSocketServer(TCPClient tcpConnection, string ip, int port, Station station, DAQTask task)
	{
		dynamic obj = new
		{
			TCPClient = tcpConnection,
			Station = station,
			Task = task
		};
		tcpConnection.NetWork = new TcpClient();
		uint dummy = 0u;
		byte[] optionInValue = new byte[Marshal.SizeOf(dummy) * 3];
		BitConverter.GetBytes(1u).CopyTo(optionInValue, 0);
		BitConverter.GetBytes(1000u).CopyTo(optionInValue, Marshal.SizeOf(dummy));
		BitConverter.GetBytes((uint)Common.SocketClientKeepAliveInterval).CopyTo(optionInValue, Marshal.SizeOf(dummy) * 2);
		tcpConnection.NetWork.Client.IOControl(IOControlCode.KeepAliveValues, optionInValue, null);
		while (!tcpConnection.NetWork.Connected)
		{
			try
			{
				await tcpConnection.NetWork.ConnectAsync(ip, port);
				tcpConnection.SetProperties();
				tcpConnection.NetWork.GetStream().BeginRead(tcpConnection.buffer, 0, tcpConnection.buffer.Length, new AsyncCallback(TCPServerCallBack), obj);
				break;
			}
			catch
			{
				Thread.Sleep(1000);
			}
		}
	}

	/// <summary>
	/// SocketServer回调函数
	/// </summary>
	/// <param name="ar"></param>
	private void TCPServerCallBack(IAsyncResult ar)
	{
		dynamic asyncState = ar.AsyncState;
		TCPClient tCPClient = asyncState.TCPClient;
		if (tCPClient.NetWork.Connected)
		{
			try
			{
				NetworkStream stream = tCPClient.NetWork.GetStream();
				byte[] array = new byte[stream.EndRead(ar)];
				if (array.Length != 0)
				{
					Array.Copy(tCPClient.buffer, array, array.Length);
					Common.ExecuteTask(asyncState.Station, asyncState.Task, CONNECTION_POOL, ALL_DEVICES, array);
					stream.BeginRead(tCPClient.buffer, 0, tCPClient.buffer.Length, new AsyncCallback(TCPServerCallBack), asyncState);
				}
				else
				{
					tCPClient.DisConnect();
				}
			}
			catch
			{
				tCPClient.DisConnect();
			}
		}
		if (!tCPClient.NetWork.Connected)
		{
			ConnectSocketServer(tCPClient, tCPClient.IP, tCPClient.Port, asyncState.Station, asyncState.Task);
		}
	}

	/// <summary>
	/// 异步更新采集状态的文字说明
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void BW_UPDATE_WORKINGSTATUS_DoWork(object sender, DoWorkEventArgs e)
	{
		string title = Text;
		Invoke((Action)delegate
		{
			Text = title + "     采集中.";
		});
		BackgroundWorker backgroundWorker = sender as BackgroundWorker;
		try
		{
			while (!backgroundWorker.CancellationPending)
			{
				Thread.Sleep(1000);
				Invoke((Action)delegate
				{
					if (Text.Contains("...."))
					{
						Text = title + "     采集中.";
					}
					else
					{
						Text += ".";
					}
				});
			}
		}
		catch (Exception ex)
		{
			if (!backgroundWorker.CancellationPending)
			{
				LocalLog.Error("主窗口异步更新采集状态的文字说明时发生异常：" + ex.Message);
			}
		}
		finally
		{
			Invoke((Action)delegate
			{
				Text = title;
			});
		}
	}

	/// <summary>
	/// 倒计时自动开始数据采集
	/// </summary>
	private void BW_AUTODAQ_CountDown(object sender, DoWorkEventArgs e)
	{
		BackgroundWorker backgroundWorker = sender as BackgroundWorker;
		Invoke((Action)delegate
		{
			lblBeginDAQMsg.Visible = false;
			lblCountDown.Visible = true;
			pnlCountDown.Visible = true;
		});
		int seconds = Convert.ToInt32(e.Argument);
		while (!backgroundWorker.CancellationPending && seconds > 0)
		{
			Invoke((Action)delegate
			{
				lblCountDown.Text = $"{seconds--}s 后自动开始数据采集";
			});
			Application.DoEvents();
			if (backgroundWorker.CancellationPending)
			{
				return;
			}
			Thread.Sleep(1000);
		}
		if (backgroundWorker.CancellationPending || seconds > 0)
		{
			return;
		}
		Invoke((Action)delegate
		{
			btnCancelCountDown.Visible = false;
			lblCountDown.Visible = false;
			lblBeginDAQMsg.Visible = true;
			Application.DoEvents();
			List<Station> list = new List<Station>();
			string text = INIHelper.ReadValue("LaunchStations", "Ids", Common.MY_INI_PATH);
			if (string.IsNullOrEmpty(text) || text.ToUpper() == "ALL")
			{
				list = Common.GetAllStations();
			}
			else
			{
				string[] stationIds = text.Split(',');
				list = (from t in Common.GetAllStations()
					where stationIds.Contains(t.Id.ToString())
					select t).ToList();
			}
			Launch(list, autoLaunch: true);
			pnlCountDown.Visible = false;
			Application.DoEvents();
		});
	}

	/// <summary>
	/// 取消自动开始数据采集
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void btnCancelCountDown_Click(object sender, EventArgs e)
	{
		BW_AUTODAQ?.CancelAsync();
		pnlCountDown.Visible = false;
	}

	/// <summary>
	/// 异步执行任务
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void Task_DoWork(object sender, DoWorkEventArgs e)
	{
		BackgroundWorker backgroundWorker = sender as BackgroundWorker;
		DAQTask dAQTask = (DAQTask)e.Argument;
		Station station = Common.GetStation(dAQTask.StationId);
		TimeoutHelper timeoutHelper = new TimeoutHelper();
		timeoutHelper.Do = Common.ExecuteTask;
		TimeoutHelper timeoutHelper2 = timeoutHelper;
		int taskTimeout = Common.TaskTimeout;
		int millisecondsTimeout = Convert.ToInt32(dAQTask.Interval);
		while (!backgroundWorker.CancellationPending)
		{
			try
			{
				timeoutHelper2.DoWithTimeout(taskTimeout * 1000, station, dAQTask, CONNECTION_POOL, ALL_DEVICES);
			}
			catch
			{
			}
			Thread.Sleep(millisecondsTimeout);
		}
	}

	/// <summary>
	/// 开启/关闭Remoting
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsbtnRemoting_Click(object sender, EventArgs e)
	{
		if (!IS_REMOTING)
		{
			try
			{
				IDictionary properties = new Hashtable
				{
					["name"] = "WIT_REMOTING_CHANNEL",
					["port"] = 10000
				};
				IChannel chnl = new TcpChannel(properties, new BinaryClientFormatterSinkProvider(), new BinaryServerFormatterSinkProvider());
				ChannelServices.RegisterChannel(chnl, ensureSecurity: false);
				RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingHelper), "WITRemoting", WellKnownObjectMode.Singleton);
				tsbtnRemoting.Text = "关闭远程服务";
				tsbtnRemoting.ForeColor = Color.Red;
				IS_REMOTING = true;
				return;
			}
			catch (Exception ex)
			{
				LocalLog.Error("开启Remoting时发生异常：" + ex.Message);
				return;
			}
		}
		IChannel[] registeredChannels = ChannelServices.RegisteredChannels;
		IChannel[] array = registeredChannels;
		foreach (IChannel channel in array)
		{
			if (channel.ChannelName == "WIT_REMOTING_CHANNEL")
			{
				TcpChannel tcpChannel = (TcpChannel)channel;
				tcpChannel.StopListening(null);
				ChannelServices.UnregisterChannel(tcpChannel);
			}
		}
		tsbtnRemoting.Text = "开启远程服务";
		tsbtnRemoting.ForeColor = SystemColors.ControlText;
		IS_REMOTING = false;
	}

	/// <summary>
	/// 开启SocketServer
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiStartSocketServer_Click(object sender, EventArgs e)
	{
		if (!IS_SOCKETSERVER_LISTENING)
		{
			try
			{
				TCPSERVER = new TcpListener(IPAddress.Any, 10001);
				TCPSERVER.Start();
				TCPSERVER.BeginAcceptTcpClient(TCPClientAcceptor, TCPSERVER);
				tsbtnSocketServer.Text = "关闭Socket服务";
				tsbtnSocketServer.ForeColor = Color.Red;
				tsmiStartSocketServer.Enabled = false;
				tsmiStopSocketServer.Enabled = true;
				IS_SOCKETSERVER_LISTENING = true;
			}
			catch (Exception ex)
			{
				LocalLog.Error("开启Socket服务时发生异常：" + ex.Message);
			}
		}
	}

	/// <summary>
	/// 关闭SocketServer
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiStopSocketServer_Click(object sender, EventArgs e)
	{
		if (IS_SOCKETSERVER_LISTENING)
		{
			tsmiStopSocketServer.Enabled = false;
			TCPSERVER.Stop();
		}
	}

	/// <summary>
	/// 客户端连接初始化
	/// </summary>
	/// <param name="ar"></param>
	private void TCPClientAcceptor(IAsyncResult ar)
	{
		TcpListener tcpListener = ar.AsyncState as TcpListener;
		try
		{
			TCPClient client = new TCPClient
			{
				NetWork = tcpListener.EndAcceptTcpClient(ar)
			};
			Invoke((Action)delegate
			{
				tscmbSocketClients.Items.Add(client);
				SOCKETCLIENTS.Add(client);
				Common.SOCKETSERVER_MONITOR_FORM?.AddClient(client);
			});
			client.NetWork.GetStream().BeginRead(client.buffer, 0, client.buffer.Length, TCPClientCallBack, client);
			tcpListener.BeginAcceptTcpClient(TCPClientAcceptor, tcpListener);
		}
		catch (ObjectDisposedException)
		{
			Invoke((Action)delegate
			{
				foreach (object item in tscmbSocketClients.Items)
				{
					if (item.GetType() == typeof(TCPClient))
					{
						((TCPClient)item).DisConnect();
					}
				}
				tscmbSocketClients.Items.Clear();
				SOCKETCLIENTS.Clear();
				InitSocketClientList();
				Common.SOCKETSERVER_MONITOR_FORM?.ClearClients();
				tsbtnSocketServer.Text = "开启Scoket服务";
				tsbtnSocketServer.ForeColor = SystemColors.ControlText;
				tsmiStartSocketServer.Enabled = true;
				IS_SOCKETSERVER_LISTENING = false;
			});
		}
		catch (Exception ex2)
		{
			MessageBox.Show(ex2.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
		}
	}

	/// <summary>
	/// 客户端通讯回调函数
	/// </summary>
	/// <param name="ar"></param>
	private void TCPClientCallBack(IAsyncResult ar)
	{
		TCPClient client = (TCPClient)ar.AsyncState;
		if (!client.NetWork.Connected)
		{
			return;
		}
		try
		{
			NetworkStream stream = client.NetWork.GetStream();
			byte[] receiveData = new byte[stream.EndRead(ar)];
			if (receiveData.Length != 0)
			{
				Array.Copy(client.buffer, receiveData, receiveData.Length);
				Invoke((Action)delegate
				{
					Common.SOCKETSERVER_MONITOR_FORM?.WriteMsg(client, receiveData, SocketServerMonitorForm.MsgType.Receive);
				});
				Stopwatch stopwatch = new Stopwatch();
				stopwatch.Start();
				int logId = -1;
				try
				{
					if (Common.SocketServerNeedLog)
					{
						logId = Common.AddLogProcess("Socket服务", "");
						Common.AddLogProcessDetail(logId, "监听到Socket客户端：" + client.Name + " \rHex：" + receiveData.ToHexStr() + "\rEncoding：" + Encoding.UTF8.GetString(receiveData));
					}
					DAQArg dAQArg = new DAQArg(Common.SocketServerNeedLog, logId);
					dAQArg.Values.Add(Common.SocketServerMsgIdentifier, receiveData);
					dAQArg.Values.Add("IP", client.IP);
					dAQArg.Values.Add("Port", client.Port);
					DAQResult dAQResult = null;
					if (!string.IsNullOrEmpty(Common.SocketServerMethodName))
					{
						object obj = null;
						MethodInfo methodInfo = null;
						if (Common.METHOD_POOL.ContainsKey(Common.SocketServerNamespace) && Common.METHOD_POOL[Common.SocketServerNamespace].Keys.Any((string t) => t == Common.SocketServerClassName) && Common.METHOD_POOL[Common.SocketServerNamespace][Common.SocketServerClassName].Keys.Any((MethodInfo t) => t.Name == Common.SocketServerMethodName))
						{
							methodInfo = Common.METHOD_POOL[Common.SocketServerNamespace][Common.SocketServerClassName].Keys.FirstOrDefault((MethodInfo t) => t.Name == Common.SocketServerMethodName);
							obj = Common.METHOD_POOL[Common.SocketServerNamespace][Common.SocketServerClassName][methodInfo];
						}
						else
						{
							Assembly assembly = Assembly.LoadFrom(Application.ExecutablePath);
							Type[] types = assembly.GetTypes();
							Type[] array = types;
							foreach (Type type in array)
							{
								if (!typeof(IIdentity).IsAssignableFrom(type))
								{
									continue;
								}
								obj = Activator.CreateInstance(type);
								MethodInfo[] methods = type.GetMethods();
								if (string.IsNullOrEmpty(Common.SocketServerClassName) && string.IsNullOrEmpty(Common.SocketServerNamespace))
								{
									methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == Common.SocketServerMethodName);
								}
								else if (!string.IsNullOrEmpty(Common.SocketServerClassName) && string.IsNullOrEmpty(Common.SocketServerNamespace))
								{
									if (!(type.Name == Common.SocketServerClassName))
									{
										continue;
									}
									methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == Common.SocketServerMethodName);
								}
								else if (string.IsNullOrEmpty(Common.SocketServerClassName) && !string.IsNullOrEmpty(Common.SocketServerNamespace))
								{
									if (!(type.Namespace == Common.SocketServerNamespace))
									{
										continue;
									}
									methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == Common.SocketServerMethodName);
								}
								else if (!string.IsNullOrEmpty(Common.SocketServerClassName) && !string.IsNullOrEmpty(Common.SocketServerNamespace))
								{
									if (!(type.Name == Common.SocketServerClassName) || !(type.Namespace == Common.SocketServerNamespace))
									{
										continue;
									}
									methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == Common.SocketServerMethodName);
								}
								if (!(methodInfo != null))
								{
									continue;
								}
								if (Common.METHOD_POOL.ContainsKey(Common.SocketServerNamespace))
								{
									if (Common.METHOD_POOL[Common.SocketServerNamespace].ContainsKey(Common.SocketServerClassName))
									{
										Common.METHOD_POOL[Common.SocketServerNamespace][Common.SocketServerClassName].Add(methodInfo, obj);
										break;
									}
									Common.METHOD_POOL[Common.SocketServerNamespace].Add(Common.SocketServerClassName, new Dictionary<MethodInfo, object> { { methodInfo, obj } });
								}
								else
								{
									Common.METHOD_POOL.Add(Common.SocketServerNamespace, new Dictionary<string, Dictionary<MethodInfo, object>> { 
									{
										Common.SocketServerClassName,
										new Dictionary<MethodInfo, object> { { methodInfo, obj } }
									} });
								}
								break;
							}
						}
						if (obj == null)
						{
							throw new Exception("类实例为null");
						}
						if (methodInfo == null)
						{
							throw new Exception("未找到方法[" + Common.SocketServerMethodName + "]");
						}
						dAQResult = (DAQResult)methodInfo.Invoke(obj, new object[1] { dAQArg });
						if (dAQResult == null)
						{
							throw new Exception("方法[" + Common.SocketServerMethodName + "]返回结果为null");
						}
						if (Common.SocketServerNeedLog)
						{
							if (dAQResult.Result)
							{
								Common.AddLogProcessDetail(logId, "方法[" + Common.SocketServerMethodName + "]执行成功。\r返回值：" + JsonConvert.SerializeObject(dAQResult.Values));
							}
							else
							{
								Common.AddLogProcessDetail(logId, "方法[" + Common.SocketServerMethodName + "]执行失败:" + dAQResult.ErrMsg);
							}
						}
					}
					if (dAQResult != null && dAQResult.Result)
					{
						if (dAQResult.Values.ContainsKey(Common.SocketServerMsgIdentifier))
						{
							if (Common.SocketServerNeedLog)
							{
								Common.AddLogProcessDetail(logId, $"尝试向客户端发送数据：{dAQResult.Values[Common.SocketServerMsgIdentifier]}");
							}
							byte[] sendData = null;
							if (dAQResult.Values[Common.SocketServerMsgIdentifier].GetType() == typeof(byte[]))
							{
								sendData = (byte[])dAQResult.Values[Common.SocketServerMsgIdentifier];
							}
							else
							{
								sendData = Encoding.UTF8.GetBytes(dAQResult.Values[Common.SocketServerMsgIdentifier].ToString());
							}
							int num = client.NetWork.Client.Send(sendData);
							if (num == sendData.Length)
							{
								if (Common.SocketServerNeedLog)
								{
									Common.AddLogProcessDetail(logId, "发送成功");
								}
								Invoke((Action)delegate
								{
									Common.SOCKETSERVER_MONITOR_FORM?.WriteMsg(client, sendData, SocketServerMonitorForm.MsgType.Send);
								});
							}
							else if (Common.SocketServerNeedLog)
							{
								Common.AddLogProcessDetail(logId, $"发送失败：需要发送的字节数为{sendData.Length}，实际发送的字节数为{num}");
							}
						}
						else if (Common.SocketServerNeedLog)
						{
							Common.AddLogProcessDetail(logId, "DAQResult.Values中不存在键值\"" + Common.SocketServerMsgIdentifier + "\"，无需向客户端发送数据。");
						}
					}
				}
				catch (Exception ex)
				{
					if (Common.SocketServerNeedLog)
					{
						Common.AddLogProcessDetail(logId, ex.Message);
					}
				}
				finally
				{
					stopwatch.Stop();
					if (Common.SocketServerNeedLog)
					{
						Common.AddLogProcessDetail(logId, "结束本次监听");
						Common.FinishLogProcess(logId, stopwatch.Elapsed.TotalSeconds);
					}
				}
				stream.BeginRead(client.buffer, 0, client.buffer.Length, TCPClientCallBack, client);
			}
			else
			{
				client.DisConnect();
				Invoke((Action)delegate
				{
					tscmbSocketClients.Items.Remove(client);
					SOCKETCLIENTS.Remove(client);
					Common.SOCKETSERVER_MONITOR_FORM?.RemoveClient(client);
				});
			}
		}
		catch
		{
			client.DisConnect();
			Invoke((Action)delegate
			{
				tscmbSocketClients.Items.Remove(client);
				SOCKETCLIENTS.Remove(client);
				Common.SOCKETSERVER_MONITOR_FORM?.RemoveClient(client);
			});
		}
	}

	/// <summary>
	/// SocketServer监控
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiSocketServerMonitor_Click(object sender, EventArgs e)
	{
		if (Common.SOCKETSERVER_MONITOR_FORM == null)
		{
			Common.SOCKETSERVER_MONITOR_FORM = new SocketServerMonitorForm(SOCKETCLIENTS)
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.SOCKETSERVER_MONITOR_FORM.Disposed += delegate
			{
				Common.SOCKETSERVER_MONITOR_FORM = null;
			};
			Common.SOCKETSERVER_MONITOR_FORM.SetCenter();
			Common.SOCKETSERVER_MONITOR_FORM.Show();
		}
		else
		{
			if (!Common.SOCKETSERVER_MONITOR_FORM.Visible)
			{
				Common.SOCKETSERVER_MONITOR_FORM.Visible = true;
			}
			if (Common.SOCKETSERVER_MONITOR_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.SOCKETSERVER_MONITOR_FORM.WindowState = FormWindowState.Normal;
			}
			Common.SOCKETSERVER_MONITOR_FORM.Activate();
		}
	}

	/// <summary>
	/// SocketServer配置
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiSocketServerConfig_Click(object sender, EventArgs e)
	{
		SocketServerConfigForm socketServerConfigForm = new SocketServerConfigForm
		{
			Icon = base.Icon,
			StartPosition = FormStartPosition.CenterParent
		};
		socketServerConfigForm.SaveSocketServerConfig += SocketServerConfigForm_SaveSocketServerConfig;
		socketServerConfigForm.ShowDialog();
	}

	/// <summary>
	/// 保存SocketServer配置
	/// </summary>
	/// <param name="needLog"></param>
	/// <param name="nameSpace"></param>
	/// <param name="className"></param>
	/// <param name="methodName"></param>
	/// <param name="identifier"></param>
	private void SocketServerConfigForm_SaveSocketServerConfig(bool needLog, string nameSpace, string className, string methodName, string identifier)
	{
		XmlDocument xmlDocument = new XmlDocument();
		xmlDocument.Load(Common.CONFIG_FILE_FULL_PATH);
		XmlElement documentElement = xmlDocument.DocumentElement;
		XmlElement xmlElement = (XmlElement)documentElement.SelectSingleNode("SocketServer");
		xmlElement.SelectSingleNode("NeedLog").InnerText = needLog.ToString();
		if (xmlElement.SelectSingleNode("Namespace") == null)
		{
			XmlNode refChild = xmlElement.SelectSingleNode("NeedLog");
			XmlElement newChild = xmlDocument.CreateElement("Namespace");
			xmlElement.InsertAfter(newChild, refChild);
		}
		xmlElement.SelectSingleNode("Namespace").InnerText = nameSpace;
		xmlElement.SelectSingleNode("ClassName").InnerText = className;
		xmlElement.SelectSingleNode("MethodName").InnerText = methodName;
		xmlElement.SelectSingleNode("Identifier").InnerText = identifier;
		xmlDocument.Save(Common.CONFIG_FILE_FULL_PATH);
	}

	/// <summary>
	/// 自定义菜单的点击事件
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void CustomMenu_Click(object sender, EventArgs e)
	{
		CustomMenu customMenu = null;
		if (sender.GetType() == typeof(ToolStripMenuItem))
		{
			customMenu = (CustomMenu)(sender as ToolStripMenuItem).Tag;
		}
		else if (sender.GetType() == typeof(ToolStripDropDownButton))
		{
			customMenu = (CustomMenu)(sender as ToolStripDropDownButton).Tag;
		}
		else
		{
			if (!(sender.GetType() == typeof(ToolStripButton)))
			{
				throw new Exception("未知的自定义菜单类型：" + sender.GetType().FullName);
			}
			customMenu = (CustomMenu)(sender as ToolStripButton).Tag;
		}
		if (!string.IsNullOrEmpty(customMenu.MethodName))
		{
			object obj = null;
			MethodInfo methodInfo = null;
			if (Common.METHOD_POOL.ContainsKey(customMenu.Namespace) && Common.METHOD_POOL[customMenu.Namespace].Keys.Any((string t) => t == customMenu.ClassName) && Common.METHOD_POOL[customMenu.Namespace][customMenu.ClassName].Keys.Any((MethodInfo t) => t.Name == customMenu.MethodName))
			{
				methodInfo = Common.METHOD_POOL[customMenu.Namespace][customMenu.ClassName].Keys.FirstOrDefault((MethodInfo t) => t.Name == customMenu.MethodName);
				obj = Common.METHOD_POOL[customMenu.Namespace][customMenu.ClassName][methodInfo];
			}
			else
			{
				Assembly assembly = Assembly.LoadFrom(Application.ExecutablePath);
				Type[] types = assembly.GetTypes();
				Type[] array = types;
				foreach (Type type in array)
				{
					if (!typeof(IIdentity).IsAssignableFrom(type))
					{
						continue;
					}
					obj = Activator.CreateInstance(type);
					MethodInfo[] methods = type.GetMethods();
					if (string.IsNullOrEmpty(customMenu.ClassName) && string.IsNullOrEmpty(customMenu.Namespace))
					{
						methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == customMenu.MethodName);
					}
					else if (!string.IsNullOrEmpty(customMenu.ClassName) && string.IsNullOrEmpty(customMenu.Namespace))
					{
						if (!(type.Name == customMenu.ClassName))
						{
							continue;
						}
						methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == customMenu.MethodName);
					}
					else if (string.IsNullOrEmpty(customMenu.ClassName) && !string.IsNullOrEmpty(customMenu.Namespace))
					{
						if (!(type.Namespace == customMenu.Namespace))
						{
							continue;
						}
						methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == customMenu.MethodName);
					}
					else if (!string.IsNullOrEmpty(customMenu.ClassName) && !string.IsNullOrEmpty(customMenu.Namespace))
					{
						if (!(type.Name == customMenu.ClassName) || !(type.Namespace == customMenu.Namespace))
						{
							continue;
						}
						methodInfo = methods.FirstOrDefault((MethodInfo t) => t.Name == customMenu.MethodName);
					}
					if (!(methodInfo != null))
					{
						continue;
					}
					if (Common.METHOD_POOL.ContainsKey(customMenu.Namespace))
					{
						if (Common.METHOD_POOL[customMenu.Namespace].ContainsKey(customMenu.ClassName))
						{
							Common.METHOD_POOL[customMenu.Namespace][customMenu.ClassName].Add(methodInfo, obj);
							break;
						}
						Common.METHOD_POOL[customMenu.Namespace].Add(customMenu.ClassName, new Dictionary<MethodInfo, object> { { methodInfo, obj } });
					}
					else
					{
						Common.METHOD_POOL.Add(customMenu.Namespace, new Dictionary<string, Dictionary<MethodInfo, object>> { 
						{
							customMenu.ClassName,
							new Dictionary<MethodInfo, object> { { methodInfo, obj } }
						} });
					}
					break;
				}
			}
			if (obj == null)
			{
				MessageBox.Show("类实例为null");
				return;
			}
			if (methodInfo == null)
			{
				MessageBox.Show("未找到方法[" + customMenu.MethodName + "]");
				return;
			}
			int num = methodInfo.GetParameters().Length;
			if (num > 0)
			{
				MessageBox.Show($"方法[{customMenu.MethodName}]具有{num}个参数，自定义菜单点击事件目前不支持传递参数。");
			}
			else
			{
				methodInfo.Invoke(obj, new object[0]);
			}
		}
		else
		{
			if (string.IsNullOrEmpty(customMenu.ClassName))
			{
				return;
			}
			Assembly assembly2 = Assembly.LoadFrom(Application.ExecutablePath);
			Type[] types2 = assembly2.GetTypes();
			if (types2.Any((Type t) => t.Name == customMenu.ClassName))
			{
				object obj2 = null;
				if (string.IsNullOrEmpty(customMenu.Namespace))
				{
					obj2 = assembly2.CreateInstance(types2.FirstOrDefault((Type t) => t.Name == customMenu.ClassName).FullName);
				}
				else
				{
					foreach (Type item in types2.Where((Type t) => t.Name == customMenu.ClassName))
					{
						if (item.Namespace == customMenu.Namespace)
						{
							obj2 = assembly2.CreateInstance(item.FullName);
							break;
						}
					}
					if (obj2 == null)
					{
						MessageBox.Show("未在指定的命名空间[" + customMenu.Namespace + "]下找到类[" + customMenu.ClassName + "]");
						return;
					}
				}
				if (obj2.GetType().BaseType == typeof(Form))
				{
					if (customMenu.AllowRepeat)
					{
						Form form = (Form)obj2;
						form.WindowState = customMenu.WindowState;
						form.SetCenter();
						form.Show();
						return;
					}
					bool flag = false;
					foreach (Form openForm in Application.OpenForms)
					{
						if (openForm.Name == customMenu.ClassName && openForm.CanFocus)
						{
							flag = true;
							if (!openForm.Visible)
							{
								openForm.Visible = true;
							}
							if (openForm.WindowState == FormWindowState.Minimized)
							{
								openForm.WindowState = FormWindowState.Normal;
							}
							openForm.Activate();
							break;
						}
					}
					if (!flag)
					{
						Form form3 = (Form)obj2;
						form3.WindowState = customMenu.WindowState;
						form3.SetCenter();
						form3.Show();
					}
				}
				else if (obj2.GetType().BaseType == typeof(UserControl))
				{
					if (customMenu.AllowRepeat)
					{
						UserControl customUC2 = (UserControl)obj2;
						customUC2.Dock = customMenu.Dock;
						CustomForm customForm = new CustomForm
						{
							Icon = base.Icon,
							Text = customMenu.Text,
							WindowState = customMenu.WindowState
						};
						customForm.Controls.Add(customUC2);
						customForm.Disposed += delegate
						{
							customUC2.Dispose();
						};
						customForm.SetCenter();
						customForm.Show();
						return;
					}
					bool flag2 = false;
					foreach (Form openForm2 in Application.OpenForms)
					{
						if (openForm2.Name == typeof(CustomForm).Name && openForm2.Controls.Count == 1 && openForm2.Controls[0].Name == customMenu.ClassName && openForm2.CanFocus)
						{
							flag2 = true;
							if (!openForm2.Visible)
							{
								openForm2.Visible = true;
							}
							if (openForm2.WindowState == FormWindowState.Minimized)
							{
								openForm2.WindowState = FormWindowState.Normal;
							}
							openForm2.Activate();
							break;
						}
					}
					if (!flag2)
					{
						UserControl customUC = (UserControl)obj2;
						customUC.Dock = customMenu.Dock;
						CustomForm customForm2 = new CustomForm
						{
							Icon = base.Icon,
							Text = customMenu.Text,
							WindowState = customMenu.WindowState
						};
						customForm2.Controls.Add(customUC);
						customForm2.Disposed += delegate
						{
							customUC.Dispose();
						};
						customForm2.SetCenter();
						customForm2.Show();
					}
				}
				else
				{
					MessageBox.Show("指定的类[" + customMenu.ClassName + "]不是一个Form/UserControl");
				}
			}
			else
			{
				MessageBox.Show("程序发生异常：未找到名为" + customMenu.ClassName + "的类");
			}
		}
	}

	/// <summary>
	/// 双击托盘图标显示程序窗口
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
	{
		if (e.Button == MouseButtons.Left)
		{
			tsmiShow_Click(null, null);
		}
	}

	/// <summary>
	/// 显示
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiShow_Click(object sender, EventArgs e)
	{
		foreach (Form openForm in Application.OpenForms)
		{
			if (openForm.Name != base.Name && openForm.CanFocus)
			{
				if (!openForm.Visible)
				{
					openForm.Visible = true;
				}
				if (openForm.WindowState == FormWindowState.Minimized)
				{
					openForm.WindowState = FormWindowState.Normal;
				}
				openForm.Activate();
			}
		}
		if (!base.Visible)
		{
			base.Visible = true;
		}
		if (base.WindowState == FormWindowState.Minimized)
		{
			base.WindowState = FormWindowState.Normal;
		}
		Activate();
	}

	/// <summary>
	/// 数据监控
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiMonitor_Click(object sender, EventArgs e)
	{
		ShowMonitorForm();
	}

	/// <summary>
	/// 查看日志
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiViewLog_Click(object sender, EventArgs e)
	{
		if (Common.LOGVIEW_FORM == null)
		{
			Common.LOGVIEW_FORM = new LogViewForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.LOGVIEW_FORM.Disposed += delegate
			{
				Common.LOGVIEW_FORM = null;
			};
			Common.LOGVIEW_FORM.SetCenter();
			Common.LOGVIEW_FORM.Show();
		}
		else
		{
			if (!Common.LOGVIEW_FORM.Visible)
			{
				Common.LOGVIEW_FORM.Visible = true;
			}
			if (Common.LOGVIEW_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.LOGVIEW_FORM.WindowState = FormWindowState.Normal;
			}
			Common.LOGVIEW_FORM.Activate();
		}
	}

	/// <summary>
	/// 设备管理
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiDeviceMgr_Click(object sender, EventArgs e)
	{
		if (Common.DEVICEMGR_FORM == null)
		{
			Common.DEVICEMGR_FORM = new DeviceMgrForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.DEVICEMGR_FORM.Disposed += delegate
			{
				Common.DEVICEMGR_FORM = null;
			};
			Common.DEVICEMGR_FORM.SetCenter();
			Common.DEVICEMGR_FORM.Show();
		}
		else
		{
			if (!Common.DEVICEMGR_FORM.Visible)
			{
				Common.DEVICEMGR_FORM.Visible = true;
			}
			if (Common.DEVICEMGR_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.DEVICEMGR_FORM.WindowState = FormWindowState.Normal;
			}
			Common.DEVICEMGR_FORM.Activate();
		}
	}

	/// <summary>
	/// 站点管理
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiStationMgr_Click(object sender, EventArgs e)
	{
		if (Common.STATIONMGR_FORM == null)
		{
			Common.STATIONMGR_FORM = new StationMgrForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.STATIONMGR_FORM.Disposed += delegate
			{
				Common.STATIONMGR_FORM = null;
			};
			Common.STATIONMGR_FORM.SetCenter();
			Common.STATIONMGR_FORM.Show();
		}
		else
		{
			if (!Common.STATIONMGR_FORM.Visible)
			{
				Common.STATIONMGR_FORM.Visible = true;
			}
			if (Common.STATIONMGR_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.STATIONMGR_FORM.WindowState = FormWindowState.Normal;
			}
			Common.STATIONMGR_FORM.Activate();
		}
	}

	/// <summary>
	/// 采集项和任务管理
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiDAQMgr_Click(object sender, EventArgs e)
	{
		if (Common.DAQMGR_FORM == null)
		{
			Common.DAQMGR_FORM = new DAQMgrForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.DAQMGR_FORM.Disposed += delegate
			{
				Common.DAQMGR_FORM = null;
			};
			Common.DAQMGR_FORM.SetCenter();
			Common.DAQMGR_FORM.Show();
		}
		else
		{
			if (!Common.DAQMGR_FORM.Visible)
			{
				Common.DAQMGR_FORM.Visible = true;
			}
			if (Common.DAQMGR_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.DAQMGR_FORM.WindowState = FormWindowState.Normal;
			}
			Common.DAQMGR_FORM.Activate();
		}
	}

	/// <summary>
	/// 程序设置
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiSetting_Click(object sender, EventArgs e)
	{
		if (Common.SETTING_FORM == null)
		{
			Common.SETTING_FORM = new SettingForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.SETTING_FORM.Disposed += delegate
			{
				Common.SETTING_FORM = null;
			};
			Common.SETTING_FORM.SetCenter();
			Common.SETTING_FORM.Show();
		}
		else
		{
			if (!Common.SETTING_FORM.Visible)
			{
				Common.SETTING_FORM.Visible = true;
			}
			if (Common.SETTING_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.SETTING_FORM.WindowState = FormWindowState.Normal;
			}
			Common.SETTING_FORM.Activate();
		}
	}

	/// <summary>
	/// About
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiAbout_Click(object sender, EventArgs e)
	{
		Version version = Assembly.GetExecutingAssembly().GetName().Version;
		string text = "      苏州德星云智能装备有限公司自主研发的数据采集平台，支持市面上的各种主流PLC以及所有支持OPCUA、ModbusTcp、S7协议的其它设备。\r      本软件受国家计算机软件著作权保护，必须经苏州德星云智能装备有限公司商务授权才可获得使用权。任何单位及个人不得以任何形式私自使用、分享或二次转售，违者将承担相应的法律责任。";
		MessageBox.Show(text, $"德星云数据采集平台 - v{version}", MessageBoxButtons.OK, MessageBoxIcon.None);
	}

	/// <summary>
	/// 命令窗口
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiCommand_Click(object sender, EventArgs e)
	{
		CommandForm commandForm = new CommandForm
		{
			Icon = base.Icon,
			StartPosition = FormStartPosition.Manual
		};
		commandForm.Location = new Point(0, Screen.GetWorkingArea(this).Height - commandForm.Height);
		commandForm.Show();
	}

	/// <summary>
	/// 性能监控
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiPerformance_Click(object sender, EventArgs e)
	{
		if (Common.PERFORMANCE_FORM == null)
		{
			Common.PERFORMANCE_FORM = new PerformanceForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.PERFORMANCE_FORM.Disposed += delegate
			{
				Common.PERFORMANCE_FORM = null;
			};
			Common.PERFORMANCE_FORM.SetCenter();
			Common.PERFORMANCE_FORM.Show();
		}
		else
		{
			if (!Common.PERFORMANCE_FORM.Visible)
			{
				Common.PERFORMANCE_FORM.Visible = true;
			}
			if (Common.PERFORMANCE_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.PERFORMANCE_FORM.WindowState = FormWindowState.Normal;
			}
			Common.PERFORMANCE_FORM.Activate();
		}
	}

	/// <summary>
	/// 强制回收内存
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiGCCollect_Click(object sender, EventArgs e)
	{
		WinformHelper.ClearMemory();
		MessageBox.Show("已强制回收内存");
	}

	/// <summary>
	/// 删除日志
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiDelLog_Click(object sender, EventArgs e)
	{
		if (Common.DELLOG_FORM == null)
		{
			Common.DELLOG_FORM = new DelLogForm
			{
				Icon = base.Icon,
				StartPosition = FormStartPosition.Manual
			};
			Common.DELLOG_FORM.Disposed += delegate
			{
				Common.DELLOG_FORM = null;
			};
			Common.DELLOG_FORM.SetCenter();
			Common.DELLOG_FORM.ShowDialog();
		}
		else
		{
			if (!Common.DELLOG_FORM.Visible)
			{
				Common.DELLOG_FORM.Visible = true;
			}
			if (Common.DELLOG_FORM.WindowState == FormWindowState.Minimized)
			{
				Common.DELLOG_FORM.WindowState = FormWindowState.Normal;
			}
			Common.DELLOG_FORM.Activate();
		}
	}

	/// <summary>
	/// OPCUA调试工具
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiDebuggerOPCUA_Click(object sender, EventArgs e)
	{
		FormBrowseServer formBrowseServer = new FormBrowseServer("opc.tcp://118.24.36.220:62547/DataAccessServer");
		formBrowseServer.Show();
	}

	/// <summary>
	/// 打开配置文件
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiViewConfig_Click(object sender, EventArgs e)
	{
		if (MessageBox.Show("请勿直接修改配置文件的内容，以免造成不可逆的后果！\r点击“是”表示同意。", "风险提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
		{
			Process process = new Process();
			process.StartInfo.FileName = Common.CONFIG_FILE_FULL_PATH;
			process.Start();
		}
	}

	/// <summary>
	/// 退出程序
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void tsmiExit_Click(object sender, EventArgs e)
	{
		if (DialogResult.Yes == MessageBox.Show("确认退出" + notifyIcon.Text + "？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
		{
			notifyIcon.Dispose();
			Environment.Exit(0);
		}
	}

	/// <summary>
	/// 自动备份配置文件
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void AutoBAKConfig(object sender, DoWorkEventArgs e)
	{
		BackgroundWorker backgroundWorker = sender as BackgroundWorker;
		try
		{
			int bAKInterval = Common.BAKInterval;
			while (!backgroundWorker.CancellationPending)
			{
				if (!Directory.Exists(Common.BAK_FOLDER_PATH))
				{
					Directory.CreateDirectory(Common.BAK_FOLDER_PATH);
				}
				DateTime? dateTime = null;
				string[] files = Directory.GetFiles(Common.BAK_FOLDER_PATH, "*", SearchOption.TopDirectoryOnly);
				foreach (string item in files.Where((string t) => t.Contains("daq.config")))
				{
					DateTime creationTime = File.GetCreationTime(item);
					if ((DateTime.Now - creationTime).Days > 30)
					{
						if (Directory.GetFiles(Common.BAK_FOLDER_PATH, "*", SearchOption.TopDirectoryOnly).Length > 1)
						{
							File.Delete(item);
						}
						continue;
					}
					if (dateTime.HasValue)
					{
						DateTime value = creationTime;
						DateTime? dateTime2 = dateTime;
						if (!(value > dateTime2))
						{
							continue;
						}
					}
					dateTime = creationTime;
				}
				if (!dateTime.HasValue || (DateTime.Now - dateTime.Value).Days >= bAKInterval)
				{
					File.Copy(Common.CONFIG_FILE_FULL_PATH, Common.BAK_FOLDER_PATH + "\\daq.config " + DateTime.Now.ToString("yyyy-MM-dd HHmmss"));
				}
				Thread.Sleep(3600000);
			}
		}
		catch (Exception ex)
		{
			if (!backgroundWorker.CancellationPending)
			{
				LocalLog.Error(ex.Message);
			}
		}
	}

	/// <summary>
	/// 开启设备延迟日志
	/// </summary>
	internal static void StartDelayLog()
	{
		List<Device> list = new List<Device>();
		string text = INIHelper.ReadValue("DelayLogDevices", "Ids", Common.MY_INI_PATH);
		if (!string.IsNullOrEmpty(text) && !(text.ToUpper() == "NONE"))
		{
			if (text.ToUpper() == "ALL")
			{
				list = Common.GetAllDevices();
			}
			else
			{
				string[] deviceIds = text.Split(',');
				list = (from t in Common.GetAllDevices()
					where deviceIds.Contains(t.Id.ToString())
					select t).ToList();
			}
		}
		foreach (Device item in list)
		{
			BackgroundWorker backgroundWorker = new BackgroundWorker
			{
				WorkerSupportsCancellation = true
			};
			backgroundWorker.DoWork += PingDevice_DoWork;
			backgroundWorker.RunWorkerAsync(item);
			DELAYLOG_BW_POOL.Add(backgroundWorker);
		}
		IS_DELAYLOGING = true;
	}

	private static void PingDevice_DoWork(object sender, DoWorkEventArgs e)
	{
		BackgroundWorker backgroundWorker = sender as BackgroundWorker;
		Device device = (Device)e.Argument;
		string iP = device.IP;
		int delayLogLimit = Common.DelayLogLimit;
		int pingDeviceTimeout = Common.PingDeviceTimeout;
		int pingDeviceInterval = Common.PingDeviceInterval;
		Ping ping = new Ping();
		while (!backgroundWorker.CancellationPending)
		{
			try
			{
				PingReply pingReply = ping.Send(iP, pingDeviceTimeout);
				if (pingReply.Status != 0 || pingReply.RoundtripTime >= delayLogLimit)
				{
					string empty = string.Empty;
					empty = ((pingReply.Status == IPStatus.Success) ? $"{pingReply.RoundtripTime}ms" : ((pingReply.Status != IPStatus.TimedOut) ? pingReply.Status.ToString() : "超时"));
					LocalLog.Log("Ping设备[" + device.Name + "]" + iP + "的延迟为：" + empty, "delay");
				}
			}
			catch
			{
			}
			Thread.Sleep(pingDeviceInterval);
		}
	}

	/// <summary>
	/// 停止设备延迟日志
	/// </summary>
	internal static void StopDelayLog()
	{
		foreach (BackgroundWorker item in DELAYLOG_BW_POOL)
		{
			item.CancelAsync();
		}
		DELAYLOG_BW_POOL.Clear();
		IS_DELAYLOGING = false;
	}

	/// <summary>
	/// 点击关闭时最小化到托盘
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	private void Main_FormClosing(object sender, FormClosingEventArgs e)
	{
		Hide();
		e.Cancel = true;
	}

	/// <summary>
	/// Clean up any resources being used.
	/// </summary>
	/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
	protected override void Dispose(bool disposing)
	{
		if (disposing && components != null)
		{
			components.Dispose();
		}
		base.Dispose(disposing);
	}

	/// <summary>
	/// Required method for Designer support - do not modify
	/// the contents of this method with the code editor.
	/// </summary>
	private void InitializeComponent()
	{
		this.components = new System.ComponentModel.Container();
		System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WIT.DAQ.Core.Forms.MainForm));
		this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
		this.cmsNotifyIcon = new System.Windows.Forms.ContextMenuStrip(this.components);
		this.tsmiShow = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
		this.tsmiMonitor = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiViewLog = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiConfig = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiDeviceMgr = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiStationMgr = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiDAQMgr = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
		this.tsmiSetting = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiMore = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiAbout = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiCommand = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiPerformance = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiGCCollect = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiDelLog = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiDebuggerTools = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiDebuggerOPCUA = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiViewConfig = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiExit = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripTop = new System.Windows.Forms.ToolStrip();
		this.tsbtnLaunch = new System.Windows.Forms.ToolStripButton();
		this.tsbtnRemoting = new System.Windows.Forms.ToolStripButton();
		this.tsbtnSocketServer = new System.Windows.Forms.ToolStripDropDownButton();
		this.tsmiStartSocketServer = new System.Windows.Forms.ToolStripMenuItem();
		this.tsmiStopSocketServer = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
		this.tscmbSocketClients = new System.Windows.Forms.ToolStripComboBox();
		this.tsmiSocketServerMonitor = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
		this.tsmiSocketServerConfig = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton();
		this.设备配置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.站点管理SToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.采集项任务管理TToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
		this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
		this.pnlCountDown = new System.Windows.Forms.Panel();
		this.lblBeginDAQMsg = new System.Windows.Forms.Label();
		this.lblCountDown = new System.Windows.Forms.Label();
		this.btnCancelCountDown = new System.Windows.Forms.Button();
		this.statusStripBottom = new System.Windows.Forms.StatusStrip();
		this.lblSlogon = new System.Windows.Forms.ToolStripStatusLabel();
		this.lblSplit = new System.Windows.Forms.ToolStripStatusLabel();
		this.lblPresented = new System.Windows.Forms.ToolStripStatusLabel();
		this.pbLogo = new System.Windows.Forms.PictureBox();
		this.cmsNotifyIcon.SuspendLayout();
		this.toolStripTop.SuspendLayout();
		this.pnlCountDown.SuspendLayout();
		this.statusStripBottom.SuspendLayout();
		((System.ComponentModel.ISupportInitialize)this.pbLogo).BeginInit();
		base.SuspendLayout();
		this.notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
		this.notifyIcon.ContextMenuStrip = this.cmsNotifyIcon;
		this.notifyIcon.Icon = (System.Drawing.Icon)resources.GetObject("notifyIcon.Icon");
		this.notifyIcon.Visible = true;
		this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseDoubleClick);
		this.cmsNotifyIcon.Items.AddRange(new System.Windows.Forms.ToolStripItem[9] { this.tsmiShow, this.toolStripSeparator1, this.tsmiMonitor, this.tsmiViewLog, this.tsmiConfig, this.toolStripSeparator2, this.tsmiSetting, this.tsmiMore, this.tsmiExit });
		this.cmsNotifyIcon.Name = "cmsNotifyIcon";
		this.cmsNotifyIcon.Size = new System.Drawing.Size(141, 170);
		this.tsmiShow.Name = "tsmiShow";
		this.tsmiShow.Size = new System.Drawing.Size(140, 22);
		this.tsmiShow.Text = "显示(&S)";
		this.tsmiShow.Click += new System.EventHandler(tsmiShow_Click);
		this.toolStripSeparator1.Name = "toolStripSeparator1";
		this.toolStripSeparator1.Size = new System.Drawing.Size(137, 6);
		this.tsmiMonitor.Name = "tsmiMonitor";
		this.tsmiMonitor.Size = new System.Drawing.Size(140, 22);
		this.tsmiMonitor.Text = "数据监控";
		this.tsmiMonitor.Click += new System.EventHandler(tsmiMonitor_Click);
		this.tsmiViewLog.Image = global::WIT_DAQ_Core_Properties_Resour.log;
		this.tsmiViewLog.Name = "tsmiViewLog";
		this.tsmiViewLog.Size = new System.Drawing.Size(140, 22);
		this.tsmiViewLog.Text = "查看日志";
		this.tsmiViewLog.Click += new System.EventHandler(tsmiViewLog_Click);
		this.tsmiConfig.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[3] { this.tsmiDeviceMgr, this.tsmiStationMgr, this.tsmiDAQMgr });
		this.tsmiConfig.Name = "tsmiConfig";
		this.tsmiConfig.Size = new System.Drawing.Size(140, 22);
		this.tsmiConfig.Text = "业务配置(&C)";
		this.tsmiDeviceMgr.Name = "tsmiDeviceMgr";
		this.tsmiDeviceMgr.Size = new System.Drawing.Size(182, 22);
		this.tsmiDeviceMgr.Text = "设备管理(&D)";
		this.tsmiDeviceMgr.Click += new System.EventHandler(tsmiDeviceMgr_Click);
		this.tsmiStationMgr.Name = "tsmiStationMgr";
		this.tsmiStationMgr.Size = new System.Drawing.Size(182, 22);
		this.tsmiStationMgr.Text = "站点管理(&S)";
		this.tsmiStationMgr.Click += new System.EventHandler(tsmiStationMgr_Click);
		this.tsmiDAQMgr.Name = "tsmiDAQMgr";
		this.tsmiDAQMgr.Size = new System.Drawing.Size(182, 22);
		this.tsmiDAQMgr.Text = "采集项&&任务管理(&I)";
		this.tsmiDAQMgr.Click += new System.EventHandler(tsmiDAQMgr_Click);
		this.toolStripSeparator2.Name = "toolStripSeparator2";
		this.toolStripSeparator2.Size = new System.Drawing.Size(137, 6);
		this.tsmiSetting.Image = global::WIT_DAQ_Core_Properties_Resour.setting;
		this.tsmiSetting.Name = "tsmiSetting";
		this.tsmiSetting.Size = new System.Drawing.Size(140, 22);
		this.tsmiSetting.Text = "程序设置";
		this.tsmiSetting.Click += new System.EventHandler(tsmiSetting_Click);
		this.tsmiMore.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[7] { this.tsmiAbout, this.tsmiCommand, this.tsmiPerformance, this.tsmiGCCollect, this.tsmiDelLog, this.tsmiDebuggerTools, this.tsmiViewConfig });
		this.tsmiMore.Name = "tsmiMore";
		this.tsmiMore.Size = new System.Drawing.Size(140, 22);
		this.tsmiMore.Text = "更多(&M)";
		this.tsmiAbout.Name = "tsmiAbout";
		this.tsmiAbout.Size = new System.Drawing.Size(148, 22);
		this.tsmiAbout.Text = "关于(&A)";
		this.tsmiAbout.Click += new System.EventHandler(tsmiAbout_Click);
		this.tsmiCommand.Name = "tsmiCommand";
		this.tsmiCommand.Size = new System.Drawing.Size(148, 22);
		this.tsmiCommand.Text = "命令窗口(&R)";
		this.tsmiCommand.Click += new System.EventHandler(tsmiCommand_Click);
		this.tsmiPerformance.Name = "tsmiPerformance";
		this.tsmiPerformance.Size = new System.Drawing.Size(148, 22);
		this.tsmiPerformance.Text = "性能监控";
		this.tsmiPerformance.Click += new System.EventHandler(tsmiPerformance_Click);
		this.tsmiGCCollect.Name = "tsmiGCCollect";
		this.tsmiGCCollect.Size = new System.Drawing.Size(148, 22);
		this.tsmiGCCollect.Text = "强制回收内存";
		this.tsmiGCCollect.Click += new System.EventHandler(tsmiGCCollect_Click);
		this.tsmiDelLog.Name = "tsmiDelLog";
		this.tsmiDelLog.Size = new System.Drawing.Size(148, 22);
		this.tsmiDelLog.Text = "删除日志";
		this.tsmiDelLog.Click += new System.EventHandler(tsmiDelLog_Click);
		this.tsmiDebuggerTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[1] { this.tsmiDebuggerOPCUA });
		this.tsmiDebuggerTools.Name = "tsmiDebuggerTools";
		this.tsmiDebuggerTools.Size = new System.Drawing.Size(148, 22);
		this.tsmiDebuggerTools.Text = "调试工具";
		this.tsmiDebuggerTools.Visible = false;
		this.tsmiDebuggerOPCUA.Name = "tsmiDebuggerOPCUA";
		this.tsmiDebuggerOPCUA.Size = new System.Drawing.Size(166, 22);
		this.tsmiDebuggerOPCUA.Text = "OPCUA调试工具";
		this.tsmiDebuggerOPCUA.Click += new System.EventHandler(tsmiDebuggerOPCUA_Click);
		this.tsmiViewConfig.Name = "tsmiViewConfig";
		this.tsmiViewConfig.Size = new System.Drawing.Size(148, 22);
		this.tsmiViewConfig.Text = "打开配置文件";
		this.tsmiViewConfig.Click += new System.EventHandler(tsmiViewConfig_Click);
		this.tsmiExit.Name = "tsmiExit";
		this.tsmiExit.Size = new System.Drawing.Size(140, 22);
		this.tsmiExit.Text = "退出(&X)";
		this.tsmiExit.Click += new System.EventHandler(tsmiExit_Click);
		this.toolStripTop.AutoSize = false;
		this.toolStripTop.Dock = System.Windows.Forms.DockStyle.None;
		this.toolStripTop.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
		this.toolStripTop.ImeMode = System.Windows.Forms.ImeMode.NoControl;
		this.toolStripTop.Items.AddRange(new System.Windows.Forms.ToolStripItem[5] { this.tsbtnLaunch, this.tsbtnRemoting, this.tsbtnSocketServer, this.toolStripDropDownButton1, this.toolStripButton1 });
		this.toolStripTop.Location = new System.Drawing.Point(0, 0);
		this.toolStripTop.Name = "toolStripTop";
		this.toolStripTop.ShowItemToolTips = false;
		this.toolStripTop.Size = new System.Drawing.Size(500, 25);
		this.toolStripTop.TabIndex = 1;
		this.toolStripTop.Text = "toolStrip1";
		this.tsbtnLaunch.BackColor = System.Drawing.SystemColors.Control;
		this.tsbtnLaunch.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
		this.tsbtnLaunch.ForeColor = System.Drawing.SystemColors.ControlText;
		this.tsbtnLaunch.Image = (System.Drawing.Image)resources.GetObject("tsbtnLaunch.Image");
		this.tsbtnLaunch.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.tsbtnLaunch.Name = "tsbtnLaunch";
		this.tsbtnLaunch.Size = new System.Drawing.Size(36, 22);
		this.tsbtnLaunch.Text = "启动";
		this.tsbtnLaunch.ToolTipText = "启动数据采集";
		this.tsbtnLaunch.Click += new System.EventHandler(tsbtnLaunch_Click);
		this.tsbtnRemoting.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
		this.tsbtnRemoting.Image = (System.Drawing.Image)resources.GetObject("tsbtnRemoting.Image");
		this.tsbtnRemoting.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.tsbtnRemoting.Name = "tsbtnRemoting";
		this.tsbtnRemoting.Size = new System.Drawing.Size(84, 22);
		this.tsbtnRemoting.Text = "开启远程服务";
		this.tsbtnRemoting.ToolTipText = "Remoting远程读写设备";
		this.tsbtnRemoting.Click += new System.EventHandler(tsbtnRemoting_Click);
		this.tsbtnSocketServer.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
		this.tsbtnSocketServer.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[7] { this.tsmiStartSocketServer, this.tsmiStopSocketServer, this.toolStripSeparator3, this.tscmbSocketClients, this.tsmiSocketServerMonitor, this.toolStripSeparator4, this.tsmiSocketServerConfig });
		this.tsbtnSocketServer.Image = (System.Drawing.Image)resources.GetObject("tsbtnSocketServer.Image");
		this.tsbtnSocketServer.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.tsbtnSocketServer.Name = "tsbtnSocketServer";
		this.tsbtnSocketServer.Size = new System.Drawing.Size(108, 22);
		this.tsbtnSocketServer.Text = "开启Socket服务";
		this.tsmiStartSocketServer.Name = "tsmiStartSocketServer";
		this.tsmiStartSocketServer.Size = new System.Drawing.Size(181, 22);
		this.tsmiStartSocketServer.Text = "开启";
		this.tsmiStartSocketServer.Click += new System.EventHandler(tsmiStartSocketServer_Click);
		this.tsmiStopSocketServer.Name = "tsmiStopSocketServer";
		this.tsmiStopSocketServer.Size = new System.Drawing.Size(181, 22);
		this.tsmiStopSocketServer.Text = "关闭";
		this.tsmiStopSocketServer.Click += new System.EventHandler(tsmiStopSocketServer_Click);
		this.toolStripSeparator3.Name = "toolStripSeparator3";
		this.toolStripSeparator3.Size = new System.Drawing.Size(178, 6);
		this.tscmbSocketClients.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
		this.tscmbSocketClients.Name = "tscmbSocketClients";
		this.tscmbSocketClients.Size = new System.Drawing.Size(121, 25);
		this.tsmiSocketServerMonitor.Name = "tsmiSocketServerMonitor";
		this.tsmiSocketServerMonitor.Size = new System.Drawing.Size(181, 22);
		this.tsmiSocketServerMonitor.Text = "监控(&M)";
		this.tsmiSocketServerMonitor.Click += new System.EventHandler(tsmiSocketServerMonitor_Click);
		this.toolStripSeparator4.Name = "toolStripSeparator4";
		this.toolStripSeparator4.Size = new System.Drawing.Size(178, 6);
		this.tsmiSocketServerConfig.Name = "tsmiSocketServerConfig";
		this.tsmiSocketServerConfig.Size = new System.Drawing.Size(181, 22);
		this.tsmiSocketServerConfig.Text = "Socket服务配置(&C)";
		this.tsmiSocketServerConfig.Click += new System.EventHandler(tsmiSocketServerConfig_Click);
		this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
		this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[3] { this.设备配置ToolStripMenuItem, this.站点管理SToolStripMenuItem, this.采集项任务管理TToolStripMenuItem });
		this.toolStripDropDownButton1.Image = (System.Drawing.Image)resources.GetObject("toolStripDropDownButton1.Image");
		this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.toolStripDropDownButton1.Name = "toolStripDropDownButton1";
		this.toolStripDropDownButton1.Size = new System.Drawing.Size(69, 22);
		this.toolStripDropDownButton1.Text = "业务配置";
		this.设备配置ToolStripMenuItem.Name = "设备配置ToolStripMenuItem";
		this.设备配置ToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
		this.设备配置ToolStripMenuItem.Text = "设备管理(&D)";
		this.设备配置ToolStripMenuItem.Click += new System.EventHandler(tsmiDeviceMgr_Click);
		this.站点管理SToolStripMenuItem.Name = "站点管理SToolStripMenuItem";
		this.站点管理SToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
		this.站点管理SToolStripMenuItem.Text = "站点管理(&S)";
		this.站点管理SToolStripMenuItem.Click += new System.EventHandler(tsmiStationMgr_Click);
		this.采集项任务管理TToolStripMenuItem.Name = "采集项任务管理TToolStripMenuItem";
		this.采集项任务管理TToolStripMenuItem.Size = new System.Drawing.Size(182, 22);
		this.采集项任务管理TToolStripMenuItem.Text = "采集项&&任务管理(&I)";
		this.采集项任务管理TToolStripMenuItem.Click += new System.EventHandler(tsmiDAQMgr_Click);
		this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
		this.toolStripButton1.Image = (System.Drawing.Image)resources.GetObject("toolStripButton1.Image");
		this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
		this.toolStripButton1.Name = "toolStripButton1";
		this.toolStripButton1.Size = new System.Drawing.Size(60, 22);
		this.toolStripButton1.Text = "数据监控";
		this.toolStripButton1.Click += new System.EventHandler(tsmiMonitor_Click);
		this.pnlCountDown.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right;
		this.pnlCountDown.BackColor = System.Drawing.SystemColors.Control;
		this.pnlCountDown.Controls.Add(this.lblBeginDAQMsg);
		this.pnlCountDown.Controls.Add(this.lblCountDown);
		this.pnlCountDown.Controls.Add(this.btnCancelCountDown);
		this.pnlCountDown.Location = new System.Drawing.Point(0, 0);
		this.pnlCountDown.Name = "pnlCountDown";
		this.pnlCountDown.Size = new System.Drawing.Size(484, 239);
		this.pnlCountDown.TabIndex = 9;
		this.pnlCountDown.Visible = false;
		this.lblBeginDAQMsg.AutoSize = true;
		this.lblBeginDAQMsg.Font = new System.Drawing.Font("微软雅黑", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 134);
		this.lblBeginDAQMsg.ForeColor = System.Drawing.Color.Red;
		this.lblBeginDAQMsg.Location = new System.Drawing.Point(166, 107);
		this.lblBeginDAQMsg.Name = "lblBeginDAQMsg";
		this.lblBeginDAQMsg.Size = new System.Drawing.Size(153, 22);
		this.lblBeginDAQMsg.TabIndex = 2;
		this.lblBeginDAQMsg.Text = "正在启动数据采集...";
		this.lblCountDown.AutoSize = true;
		this.lblCountDown.Font = new System.Drawing.Font("微软雅黑", 12f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 134);
		this.lblCountDown.Location = new System.Drawing.Point(154, 107);
		this.lblCountDown.Name = "lblCountDown";
		this.lblCountDown.Size = new System.Drawing.Size(177, 22);
		this.lblCountDown.TabIndex = 0;
		this.lblCountDown.Text = "9s 后自动开始数据采集";
		this.btnCancelCountDown.Location = new System.Drawing.Point(205, 166);
		this.btnCancelCountDown.Name = "btnCancelCountDown";
		this.btnCancelCountDown.Size = new System.Drawing.Size(75, 23);
		this.btnCancelCountDown.TabIndex = 1;
		this.btnCancelCountDown.Text = "取消(&C)";
		this.btnCancelCountDown.UseVisualStyleBackColor = true;
		this.btnCancelCountDown.Click += new System.EventHandler(btnCancelCountDown_Click);
		this.statusStripBottom.AutoSize = false;
		this.statusStripBottom.Dock = System.Windows.Forms.DockStyle.None;
		this.statusStripBottom.Items.AddRange(new System.Windows.Forms.ToolStripItem[3] { this.lblSlogon, this.lblSplit, this.lblPresented });
		this.statusStripBottom.Location = new System.Drawing.Point(-1, 238);
		this.statusStripBottom.Name = "statusStripBottom";
		this.statusStripBottom.Size = new System.Drawing.Size(500, 25);
		this.statusStripBottom.SizingGrip = false;
		this.statusStripBottom.TabIndex = 10;
		this.lblSlogon.Name = "lblSlogon";
		this.lblSlogon.Size = new System.Drawing.Size(156, 20);
		this.lblSlogon.Text = " 德星云智能，智造改变世界";
		this.lblSplit.Name = "lblSplit";
		this.lblSplit.Size = new System.Drawing.Size(213, 20);
		this.lblSplit.Spring = true;
		this.lblPresented.Name = "lblPresented";
		this.lblPresented.Size = new System.Drawing.Size(116, 20);
		this.lblPresented.Text = "Presented by DXY ";
		this.pbLogo.Image = global::WIT_DAQ_Core_Properties_Resour.logo;
		this.pbLogo.Location = new System.Drawing.Point(14, -20);
		this.pbLogo.Name = "pbLogo";
		this.pbLogo.Size = new System.Drawing.Size(450, 280);
		this.pbLogo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
		this.pbLogo.TabIndex = 3;
		this.pbLogo.TabStop = false;
		base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 12f);
		base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
		base.ClientSize = new System.Drawing.Size(484, 261);
		base.Controls.Add(this.statusStripBottom);
		base.Controls.Add(this.toolStripTop);
		base.Controls.Add(this.pbLogo);
		base.Controls.Add(this.pnlCountDown);
		base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
		base.Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon");
		base.MaximizeBox = false;
		base.Name = "MainForm";
		base.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
		this.Text = "WIT.DAQ";
		base.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Main_FormClosing);
		base.Load += new System.EventHandler(MainForm_Load);
		base.Shown += new System.EventHandler(MainForm_Shown);
		this.cmsNotifyIcon.ResumeLayout(false);
		this.toolStripTop.ResumeLayout(false);
		this.toolStripTop.PerformLayout();
		this.pnlCountDown.ResumeLayout(false);
		this.pnlCountDown.PerformLayout();
		this.statusStripBottom.ResumeLayout(false);
		this.statusStripBottom.PerformLayout();
		((System.ComponentModel.ISupportInitialize)this.pbLogo).EndInit();
		base.ResumeLayout(false);
	}
}
